Javascript .querySelector find div by innerTEXT
OP's question is about plain JavaScript and not jQuery.
Although there are plenty of answers and I like @Pawan Nogariya answer, please check this alternative out.
You can use XPATH in JavaScript. More info on the MDN article here.
The document.evaluate()
method evaluates an XPATH query/expression. So you can pass XPATH expressions there, traverse into the HTML document and locate the desired element.
In XPATH you can select an element, by the text node like the following, whch gets the div
that has the following text node.
//div[text()="Hello World"]
To get an element that contains some text use the following:
//div[contains(., 'Hello')]
The contains()
method in XPATH takes a node as first parameter and the text to search for as second parameter.
Check this plunk here, this is an example use of XPATH in JavaScript
Here is a code snippet:
var headings = document.evaluate("//h1[contains(., 'Hello')]", document, null, XPathResult.ANY_TYPE, null );
var thisHeading = headings.iterateNext();
console.log(thisHeading); // Prints the html element in console
console.log(thisHeading.textContent); // prints the text content in console
thisHeading.innerHTML += "<br />Modified contents";
As you can see, I can grab the HTML element and modify it as I like.
Find div by inner text and adding class
I hope I have been helpful
var x = document.getElementsByTagName("div");
for ( var i = 0; i < x.length; i++) {
var y = x[i].innerHTML.indexOf('Second');
if (y>-1) {
x[i].setAttribute("class", "check");
}
}
How to find innerText or textContent of a specific dataset (data-*) using queryselector javascript?
Try this:
alert(document.querySelectorAll("[data-field='member.firstName']")[0].innerText);
Link to fiddle (ES6): https://jsfiddle.net/hcrov42e/
document.querySelectorAll get innerText of ALL selected elements at once pure javascript
The easiest way I found was to convert the nodeList to an array first then use a map:
var nodes = document.querySelectorAll("h3 em");
var list = [].slice.call(nodes);
var innertext = list.map(function(e) { return e.innerText; }).join("\n");
Select Text node using querySelector
As already answered, CSS does not provide text node selectors and thus document.querySelector
doesn't.
However, JavaScript does provide an XPath-parser by the method document.evaluate
which features many more selectors, axises and operators, e.g. text nodes as well.
let result = document.evaluate( '//div[@class="a"]/div[@class="clear"]/following-sibling::text()[1]', document, null, XPathResult.STRING_TYPE).stringValue;
console.log(result.trim());
<body> <div class="a"> <h1>some random text</h1> <div class="clear"></div> Extract This Text <p></p> But Not This Text <h2></h2> </div></body>
HTML JavaScript querySelector to find an element whose child has a specific data attribute
First use querySelectorAll
which will give an array. Then iterate over it and check and get element with required data
attribute.
After that you can use use a if
& check the content inside it
let k = document.querySelectorAll('[ data-parent=true]').forEach(function(item) { let elem = item.querySelector('[data-child-gender=true]'); if (elem !== null && elem.innerHTML.trim() === 'male') { console.log(item.id) }})
<div id="grandparent"> <div id="parent1" data-parent="true"> <div id="child1" data-child-gender="false"> male </div> </div> <div id="parent2" data-parent="true"> <div id="child2" data-child-gender="true"> female </div> </div> <div id="parent3" data-parent="false"> <div id="child3" data-child-gender="true"> female </div> </div> <div id="parent4" data-parent="true"> <div id="child4" data-child-gender="true"> male </div> </div></div>
Selecting a childnode by inner text from a NodeList
I think this approach should lead you to the solution.
Giving your HTML
<div id="search_filters">
<section class="facet clearfix"><p>something</p><ul>...</ul></section>
<section class="facet clearfix"><p>something1</p><ul>...</ul></section>
<section class="facet clearfix"><p>something2</p><ul>...</ul></section>
<section class="facet clearfix"><p>something3</p><ul>...</ul></section>
<section class="facet clearfix"><p>something4</p><ul>...</ul></section>
</div>
I would write this js
const needle = "something3";
const selection = document.querySelectorAll('section.facet.clearfix');
let i = -1;
console.info("SELECTION", selection);
let targetIndex;
while(++i < selection.length){
if(selection[i].innerHTML.indexOf(needle) > -1){
targetIndex = i;
}
}
console.info("targetIndex", targetIndex);
console.info("TARGET", selection[targetIndex]);
Then you can play and swap elements around without removing them from the DOM.
PS. Since you know the CSS classes for the elements you don't need to use the ^*
(start with) selector. I also improved that.
PART 2: ordering children li based on content
const ul = selection[targetIndex].querySelector("ul"); // Find the <ul>
const lis = ul.querySelectorAll("li"); // Find all the <li>
const sortOrder = ['text2', 'text1', 'text4', 'text3'];
i = -1; // We already declared this above
while(++i < sortOrder.length){
const li = [...lis].find((li) => li.innerHTML.indexOf(sortOrder[i]) > -1);
!!li && ul.appendChild(li);
}
This will move the elements you want (only the one listed in sortOrder
) in the order you need, based on the content and the position in sortOrder
.
Codepen Here
Why does querySelector('div span') match even though querySelector('div') does not?
console.log(p.querySelector('div'))
Finds nothing because
The querySelector() method of the Element interface returns the first element that is a descendant of the element on which it is invoked that matches the specified group of selectors. -- mdn (emphasis mine)
console.log(p.querySelector('div span'))
Matches because
The entire hierarchy of elements is considered when matching, including those outside the set of elements including baseElement and its descendants; in other words, selectors is first applied to the whole document, not the baseElement, to generate an initial list of potential elements. The resulting elements are then examined to see if they are descendants of baseElement. The first match of those remaining elements is returned by the querySelector() method. -- mdn (emphasis mine):
Thank you evolutionxbox and G-Cyrillus for your comments.
How can I select an element using its text content?
You can use below XPath to fetch span
with required text content:
//*[contains(@class, "c-partnerSelector__menu__list")]/li/p/span[.="SecondElement"]
This means the same as your CSS selector .c-partnerSelector__menu__list > li > p > span
+ predicate to examine nodes' text content
Related Topics
How to Check If the Url Contains a Given String
Iterate Over Object Literal Values
Displaying a Number in Indian Format Using JavaScript
What's the Difference Between Reflow and Repaint
Getting Key with the Highest Value from Object
In JavaScript/Jquery What Does (E) Mean
What Is {This.Props.Children} and When You Should Use It
How to Turn Nan from Parseint into 0 for an Empty String
Select All Contents of Textbox When It Receives Focus (Vanilla Js or Jquery)
How to Disable Signature Checking for Firefox Add-Ons
How to Check If an Element Is Overlapping Other Elements
How to Communicate Between Popup.Js and Background.Js in Chrome Extension
How to Wrap Async Function Calls into a Sync Function in Node.Js or JavaScript
How to Require a Controller in an Angularjs Directive
Node.Js Shell Command Execution
What Is Difference Between Axios and Fetch