How can I check if a div contains a certain word?
var divs= document.getElementsByTagName('div');
for (var i = 0, len = divs.length; i < len; ++i) {
if (divs[i].text = '*word*'){
//do somthing
}
}
doesn't work.
How can I check if a div contains a certain word?
var divs= document.getElementsByTagName('div');
for (var i = 0, len = divs.length; i < len; ++i) {
if (divs[i].text = '*word*'){
//do somthing
}
}
doesn't work.
use the indexOf function
if(divs[i].innerHTML.indexOf("word") !== -1) {
// something
}
Use includes()
:
node.textContent.includes('Some text');
if (document.getElementById('divId').innerHTML.indexOf("word") != -1) { }
Try the String.indexOf()
function: if (divs[i].text.indexOf('word') != -1) {
You have to use a comparison operator not assign a variable.
if (divs[i].text == '*word*'){
I would recommend to use indexOf
.
if (divs[i].text.indexOf('*word*') != -1){
In addition to what others said about using .indexOf()
function, I'd like to say .text
is not a div node property. User .innerHTML
if (divs[i].innerHTML.indexOf('word') > -1){}
Gosh, so many answers!
To get just the text of an element, the simple way is to use textContent
or, were not supported, innerText
. All browsers in use support one or the other (maybe both). You can also use a regular expression (indexOf works too, a RegExp is just an option) so:
var re = new RegExp('*' + word + '*');
if (re.test(div[i].innerText || div[i].textContent)) {
// div[i] contains /*word*/
}
A more robust solution would be like:
function getText(el) {
if (typeof el.textContent == 'string') {
return el.textContent;
}
if (typeof el.innerText == 'string') {
return el.innerText;
}
}
var re = new RegExp('*' + word + '*');
if (re.test(getText(div[i]))) {
// div[i] contains /*word*/
}
html :
<div id="ok">Hello world</div>
javascript :
var ok;
ok = document.getElementById("ok").innerHTML
if (ok.includes("world")) {
document.getElementById("ok").innerHTML = "its working";
}
use regexp:
if ( divs[i].textContent.match ( /\bword\b/ ) ){
//do something
}
@RobG remind me so
if ( divs[i].innerHTML.match ( /\bword\b/ ) ){
//do something
}
=3=
<ul class="single-headlines">
<li>Fixed Shipping Sek 29</li>
<li>44/5 Trustpilot</li>
<li>Fast Delivery</li>
</ul>
<script>
jQuery(".single-headlines > li:first").text(function () {
return jQuery(this).text().replace("Fixed Shipping Sek 29", "Fast fraktkostnad SEK 29");
});
jQuery(".single-headlines > li:nth-child(3)").text(function () {
return jQuery(this).text().replace("Fast Delivery", "Snabb leverans");
});
</script>
By selector Find the text which have to replace. text() return the selected text element replace() change the text.
© 2022 - 2024 — McMap. All rights reserved.