How to find element in string by class using JavaScipt? - javascript

For example I have a string with html code.
const string = `
<div>
<h1>Title</h1>
<h2>Subtitle</h2>
<div class="find-me">text</div>
</div>
`;
Expected result with JS script:
<div class="find-me">text</div>
How it's possible to do it without jquery and other libraries/frameworks ?

Try this
const string = `
<div>
<h1>Title</h1>
<h2>Subtitle</h2>
<div class="find-me">text</div>
</div>
`;
let arr = string.split('\n');
for(let i=0; i<arr.length; i++){
if(arr[i].search("find-me") != -1){
console.log(arr[i]);
}
}

you can create a temporary element and attach the string using innerHTML:
let tempElement = document.createElement("div");
tempElement.innerHTML = string;
const myElement = tempElement.querySelector(".find-me");

Related

Tag search issue in html codes rendered using DangerouslySetInnerHtml

I get data from a service with Axios. Then I take it from the Reducer on the page. I'm inviting the data I've thrown into Redux in a function. I'm parsing a String HTML code with DangerouslySetInnerHtml. And I want to call the h2 tag in the generated html.
With getElementsByTagName I get data in the form of HTMLCollection. But I can't use HTMLCollection in a forEach loop.
//code in page
<div
className="article-content"
dangerouslySetInnerHTML={{ __html: detail !== undefined && detail.content }}
/>
where the function is loaded
<div>{this._renderSideBar()}</div>
Function
var article = document.getElementsByClassName("article-content");
var h2s = article[0]
.getElementsByClassName("article-detail")[0]
.getElementsByClassName("article-content")[0]
.getElementsByTagName("h2");
console.log(h2s) // HTMLCollection 5 result
for(var i = 0; i < h2s.length; i++;){
// not working
console.log(h2s[i]);
}
I want to set up a loop here but I can't use HTMLCollection as array
I tried your code and it works after slight modification. Check below. It iterates through the HTMLCollection and prints the H2s
var article = document.getElementsByClassName("article-content");
var h2s = article[0]
.getElementsByClassName("article-detail")[0]
.getElementsByClassName("article-content")[0]
.getElementsByTagName("h2");
for(var i = 0; i < h2s.length; i++){
console.log(h2s[i]);
}
<div class="article-content">
<div class="article-detail">
<div class="article-content">
<h2>H2 1</h2>
<h2>H2 2</h2>
<h2>H2 3</h2>
<h2>H2 4</h2>
<h2>H2 5</h2>
</div>
</div>
</div>
convert the nodelist to array with follwing:
var inputList = Array.prototype.slice.call(h2s);
for(var i = 0; i < inputList .length; i++;){
// not working
console.log(h2s[i]);
}
I solved the problem.
In function
var detailText = this.props.state.blog.detail;
var parser = new DOMParser();
var htmlDoc = parser.parseFromString(detailText, "text/html");
var h2s = htmlDoc.getElementsByTagName("h2");
let items = [];
for (var i = 0; i < h2s.length; i++) {
items.push(h2s[i].innerText);
}
return items.map((row, i) => {
return (
<li key={i}>
{row}
</li>
);
});

Using vanilla javascript to hide a tag that contains certain text

I have this code that hides a div that only contains a specific word, I've been trying (with no luck) to hide any div that contains this word, but also contains more text.
Any help will be appreciated, thanks!
let divs = document.getElementsByClassName('test');
for (let x = 0; x < divs.length; x++) {
let div = divs[x];
let content = div.innerHTML.trim();
if (content == 'example') {
div.style.display = 'none';
}
}
<div class="test">
ipsum
</div>
<div class="test">
example
</div>
<div class="test">
example complete
</div>
You could use JavaScript's string.includes().
A hacky way to only remove the div containing more then only "examaple" is to have "example " in the includes(). This will only remove the div if the innerHTML has a space after "example"
let divs = document.getElementsByClassName('test');
for (let x = 0; x < divs.length; x++) {
let div = divs[x];
let content = div.innerHTML.trim();
if (content.includes('example')) {
div.style.display = 'none';
}
}
<div class="test">
ipsum
</div>
<div class="test">
example
</div>
<div class="test">
example complete
</div>
Something modern…
document.querySelectorAll('.test').forEach((element, index) => {
if (element.innerText.includes('example')) {
element.style.display = 'none';
}
})
<div class="test">ipsum</div>
<div class="test">example</div>
<div class="test">example complete</div>
Docs:
NodeList.prototype.forEach()
String.prototype.includes()
If you want to remove the div that contains the search word (checked with includes) but that also has other characters in it perhaps store the word in a variable and check to see if the text is longer than that.
let divs = document.getElementsByClassName('test');
const word = 'example';
for (let x = 0; x < divs.length; x++) {
let div = divs[x];
let content = div.innerHTML.trim();
if (content.includes(word) & content.length > word.length) {
div.style.display = 'none';
}
}
<div class="test">
ipsum
</div>
<div class="test">
example
</div>
<div class="test">
example complete
</div>
Here's a modernised version of that code.
let divs = document.querySelectorAll('.test');
const word = 'example';
divs.forEach(div => {
const { style, textContent } = div;
const trimmed = textContent.trim();
if (trimmed.includes(word) && trimmed.length > word.length) {
style.display = 'none';
}
});
<div class="test">
ipsum
</div>
<div class="test">
example
</div>
<div class="test">
example complete
</div>
When you do div.innerHTML.trim(), it takes the entirety of the div element.
https://jsfiddle.net/ucvteLq7/7/
Try to search around regular expressions, and I think, you shouldn't hide a div according its class, but you must replace what it contains. Sorry that I can't help more.

Confused creating a HTML divs using Javascript

I'm writing a code where in there is a json given and out of the key value pairs of json I need to create HTML divs.
Here is my HTML
<div id="col-md-12">
</div>
<input type="button" onclick="addDivs()" />
and my JS
function addDivs() {
var jsonInput = {
'a': '1',
'b': '2'
}
var colDiv = document.getElementById("col-md-12");
var row = document.createElement("div");
row.className = "row";
Object.keys(jsonInput).forEach(function(k) {
var string = k;
var range = jsonInput[k];
var col4Div = document.createElement("div");
col4Div.className = "col-md-4 icon-plus";
var alcohol = document.createElement("span");
alcohol.className = string;
var strong = document.createElement("strong");
strong.innerHTML = string;
var dropDownArrow = document.createElement("span");
dropDownArrow.className = "down-arrow";
alcohol.innerHTML = strong;
alcohol.innerHTML = dropDownArrow;
alcohol.innerHTML = "<br/>";
alcohol.innerHTML = range;
col4Div.innerHTML = alcohol;
row.innerHTML = col4Div;
});
colDiv.innerHTML=row;
}
when I click the button, it gives me message as [object HTMLDivElement] and in console it shows no error.
I'm really confused on what's going on in the backend. My expected output is
<div class="col-md-12">
<div class="row">
<div class="col-md-4 icon-plus">
<span class="a">
<strong>a</strong>
<span class="down-arrow"></span>
<br /> 1</span>
</div>
<div class="col-md-4 icon-plus">
<span class="b">
<strong>b</strong>
<span class="down-arrow"></span>
<br /> 2</span>
</div>
</div>
</div>
please let me know where am I going wrong and how can I fix it.
Here is a working fiddle. https://jsfiddle.net/p9e7cLg9/1/
Thanks
innerHTML deals in strings (of HTML source code). createElement deals in DOM nodes.
When you convert a DOM node to a string, you get "[object HTMLDivElement]", which isn't useful, so don't do that.
Use the appendChild method to add a DOM node as a child of an existing HTML element.

document.querySelector returns null

I use the querySelector in JS to select html markup that I filled in with a JS script. However, anytime I try to store the divs with a class of .card in the const questionCard, I get null.
Why can't I select the cards?
HTML:
<div class='card-container'></div>
JS:
const questionBlock = document.querySelector('.card-container');
const questionCard = document.querySelector('.card');
function build() {
let output = [];
...some unimportant code here...
output.push(
`
<div class='card'>
<div class='question'>${current.question}</div>
<div class='answers'>${answers.join('')}</div>
</div>
`
);
})
questionBlock.innerHTML = output;
}
build();
You need to call document.querySelector('.card') after calling build(). It cannot find HTML elements that do not exist yet.
const questionBlock = document.querySelector('.card-container');
function build() {
let output = [];
...some unimportant code here...
output.push(
`
<div class='card'>
<div class='question'>${current.question}</div>
<div class='answers'>${answers.join('')}</div>
</div>
`
);
})
questionBlock.innerHTML = output;
}
build();
const questionCard = document.querySelector('.card');
An alternative to the more correct answers is:
const questionCard = document.getElementsByClassName('card');
now: questionCard is a live HTMLCollection, and questionCard[0] will be the first element with class including card

How to loop div like angular js using pure javascript

I have use this following technique to replace sting in html.
var str = "Some html values";
var res = str.replace("{company}","Microsoft");
But i want to loop div like angular js by using pure JavaScript like shown below
{foreach value in values} <div class="test">{value}</div> {/foreach}
if anyone knows please let me know
Here is a way in vanilla JS :
var values = ["Microsoft", "Apple", "Amazon"];
var node = document.getElementById( "myDiv" );
var res="";
for (id in values){
res+="<p>"+values[id]+"</p>";
}
node.innerHTML=res;
<div id='myDiv'></div>
I have found the solution
var values = '';
var alphabet = ['a','b','c','d','e'];
var meanings = ['apple','banana','choclate','dominoes pizza','eggs']
var value = document.getElementById("test1").innerHTML;
for (var i=0; i<alphabet.length; i++) {
values += value.replace("{value}",alphabet[i]).replace("{meanings}",meanings[i]);
}
document.getElementById("test2").innerHTML = values;
<div id="test2" class="test">
<div id="test1" class="test">
<div class="test">
{value} for {meanings}
</div>
</div>
</div>

Categories

Resources