How do I get child elements from class list object? - javascript

think I have some class of same content
<div class="parentclass">
<div class="childClass">
</div>
<div class="childClass">
</div>
<div class="childClass">
</div>
</div>
<div class="parentclass">
<div class="childClass">
</div>
<div class="childClass">
</div>
<div class="childClass">
</div>
</div>
I can get all the parent class object in an array by
var pClassList= document.getElementsByClassName("parentclass");
My question is how can I access the child classes "childClass" from pClassList array calling it index like
var childClassList1= pClassList[0].getElementsByClassName("childClass");
var childClassList2= pClassList[1].getElementsByClassName("childClass");

Simply loop over the initial collection and use index of each iteration to access individual elements
var pClassList= document.getElementsByClassName("parentclass");
for(var i=0; i < pClassList.length; i++){
var parentElement = pClassList[i];
// do something to each parent as needed
// access children of parent element
var childClassList= parentElement.getElementsByClassName("childClass");
// do something with `childClassList`
for (var j= 0; j < childClassList.length; j++){
var child = childClassList[j];
// do something with each child here
}
}

Could be:
var childClassList1= pClassList[0].getElementsByClassName("childClass")[0];
var childClassList2= pClassList[1].getElementsByClassName("childClass")[0];
I prefer to use JQuery, in this case it would be.
var pClassList = $(".parentclass")
var childClassList1 = $(pClassList[0]).children().first()
var childClassList2 = $(pClassList[1]).children().first()

The following will retrieve child nodes with classname="childClass" for the first element in pClassList array:
for (var i = 0; i < pClassList[0].childNodes.length; i++) {
if (pClassList[0].childNodes[i].className == "childClass") {
//Do something with pClassList[0].childNodes[i]
}
}
You can do the same for the rest of the elements in pClassList array by iterating over each of them.

An alternative I think is you select as you want childClass is like :
var childClassList1= document.querySelector('.childClass:nth-child(2)');

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>
);
});

add div id and for attribute sequentially using js

I want to dynamically add the id and for attribute for each input and label element.
<div id="splash">
<div class="tab">
<input id="tab-1">
<label for="tab-1"><label>
</div>
<div class="tab">
<input id="tab-2">
<label for="tab-2"><label>
</div>
<div class="tab">
<input id="tab-3">
<label for="tab-3"><label>
</div>
</div>
So basically I would want the id for the input to be tab-# with the # increasing by 1 for each input field and the same for the "for=" attribute for the label.
It's super easy. Just iterate through each .tab, using each's index argument, and modify the attributes of the elements.
$('.tab').each(function (index) {
var tabName = 'tab-' + (index + 1);
$('input', this).attr('id', tabName);
$('label', this).attr('for', tabName);
});
Jsbin: http://jsbin.com/rawatag/4/edit?html,js,output
Ok.
I won't give you a straight answer but this should be more useful in future.
Basically make the container <div id=splash>
Then run this command document.getElementById("parentID").innerHTML += "Something here"
This will add the content (pay attention to. The += sign) to the div (splash)
Then, just wrap this in a loop using a counter to get the desired result
Eg: ...innerHTML += "<div id=tab-" + counter + "></div>"
Note that this can be done in raw JS. No JQuery required.
No need for jQuery here:
es5 (jsfiddle)
function assignInputsAndLabels(root) {
var children = root.children;
var tabNumber = 1;
for (var i = 0; i < children.length; i++) {
if (children[i].classList.contains('tab')) {
children[i].getElementsByTagName('input')[0].setAttribute('id', 'tab-' + tabNumber);
children[i].getElementsByTagName('label')[0].setAttribute('for', 'tab-' + tabNumber);
tabNumber++;
}
}
}
assignInputsAndLabels(document.getElementById('splash'));
es6
function assignInputsAndLabels(root) {
const children = root.children;
let tabNumber = 1;
for (let i = 0; i < children.length; i++) {
if (children[i].classList.contains('tab')) {
children[i].getElementsByTagName('input')[0].setAttribute('id', `tab-${tabNumber}`);
children[i].getElementsByTagName('label')[0].setAttribute('for', `tab-${tabNumber}`);
tabNumber++;
}
}
}
assignInputsAndLabels(document.getElementById('splash'));
The parameter to the function is the wrapper of the elements that have the class of tab. In your case, you'd pass in the DOM node of the element with id of splash. So you'd call the function like this:
assignInputsAndLabels(document.getElementById('splash'));
I have done it using javascript.Check it below
function init(){
var sel = document.getElementsByClassName("tab");
var i=1;
for(let obj of sel){
var attr = "tab-"+i;
obj.getElementsByTagName('input')[0].setAttribute("id",attr);
obj.getElementsByTagName('label')[0].setAttribute("for",attr);
i++;
}
}
addEventListener("load",init);
<div class="tab">
<input type="text">
<label></label>
</div>
<div class="tab">
<input type="text">
<label></label>
</div>

How to get value of an attribute of html element inside variable?

I use this code for get data-isAirTour attribute but always is undefined.
var tours = $('#WrapTours').find('div.tour');
var toursTmp;
var length = tours.length;
for (var i = 0; i < length; i++) {
if (tours.eq(i).value.data('isForeignTour') == isForeignTour) {
toursTmp.push(tours[i]);
}
}
html:
<div class="col-sms-6 col-sm-6 col-md-3 tour" data-isAirTour="#item.IsAirTour" data-isForeignTour="#item.IsForeignTour" data-TourType="#item.TourType">
</div>
How to solve this?
tours[i] will return DOM element. To get jQuery object use .eq(index), to get the object at index then you can use jQuery methods like .attr()
tours.eq(i).attr('data-isAirTour')
Apart from the other proposed solutions, you can also use the vanilla JS getAttribute() method, like so:
var tours = $('#WrapTours').find('div.tour');
for (var i = 0; i < tours.length; i++) {
var attr01 = tours[i].getAttribute("data-isAirTour");
console.log(attr01);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="WrapTours">
<div class="tour" data-isAirTour="yes"></div>
</div>
Alternatively, you can use dataset.isairtour (remember to keep it all in lowercase) to achieve the same result:
var tours = $('#WrapTours').find('div.tour');
for (var i = 0; i < tours.length; i++) {
var attr01 = tours[i].dataset.isairtour;
console.log(attr01);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="WrapTours">
<div class="tour" data-isAirTour="yes"></div>
</div>

How to get the text from a div which has children in it

I am currently studying JavaScript and I have the following problem. Is it possible to get only the text from a div which has children inside it? I managed to make it work only for the text which appears before the div's children.
PS: I would like to mention that I am trying to achieve this using only pure JavaScript.
var Class = document.querySelectorAll('div,b');
for (var i=0; i < Class.length; i++){
console.log(Class[i].childNodes[0].nodeValue);
}
<div class="Bio">
My name is <b>John Doe</b> and I am coming from Texas
</div>
<div class="Bio">
My name is <b>Jean Frye</b> and I am coming from Alabama
</div>
It's not very clean way, but try something like this :
//get all div's with Bio css class (You can change it)
var Class = document.querySelectorAll('.Bio');
var sp=document.getElementById('res');
var arr=[]; //I put result into array so You can use it where You need
for (var i=0; i < Class.length; i++) {
for(var x=0;x<Class[i].childNodes.length;x++) {
if(Class[i].childNodes[x].nodeValue==null) {
//get value, innerHTML, from <b>
//res.innerHTML+=Class[i].childNodes[x].innerHTML+'<br>';
arr.push(Class[i].childNodes[x].innerHTML);
} else {
//get div innerHTML (before,after every child node
//res.innerHTML+=Class[i].childNodes[x].nodeValue+'<br>';
arr.push(Class[i].childNodes[x].nodeValue);
}
}
}
//show result into that span
for(var i=0;i<arr.length;i++) {
res.innerHTML+=arr[i]+'<br>';
}
<div class="Bio">
My name is <b>John Doe</b> and I am coming from Texas
</div>
<div class="Bio">
My name is <b>Jean Frye</b> and I am coming from Alabama
</div>
<br><br>
<!-- I use this span to show result -->
<span id="res"></span>
var Class = document.querySelectorAll('div');
for (var i=0; i < Class.length; i++){
var children = [];
var boldText = Class[i].querySelectorAll('b')[0].innerText;
var otherText = Class[i].innerText.split(Class[i].querySelectorAll('b')[0].innerText)
children.push(otherText[0]);
children.push(boldText);
children.push(otherText[1]);
console.log(children);
}
Output :-
["My name is ", "John Doe", " and I am coming from Texas"]
["My name is ", "Jean Frye", " and I am coming from Alabama"]
This might do the trick.
You can use innerText to get only the text of your selected element.
var Class = document.querySelectorAll('div');
for (var i=0; i < Class.length; i++){
console.log(Class[i].innerText);
}
<div class="Bio">
My name is <b>John Doe</b> and I am coming from Texas
</div>
<div class="Bio">
My name is <b>Jean Frye</b> and I am coming from Alabama
</div>
For more information, reference the MDN article on innerText

for loop is iterating over the same value

So basically I have a set of questions(<div>s), all with the same class name and I want to simply loop through all of those classes and append the questions(<div>s) inside a container but at the minute it seems to just loop through it but only display the 1st question over and over or however many questions I put in.
if($('.option').hasClass('c_questions')){
var y = document.getElementsByClassName('c_questions');
for(var i = 0; i < y.length; i++){
$('.main-body').append($('.c_questions').html());
}
}
$('.c_questions').each(function(a){
$('.main-body').append($(this).html()+" ");
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="c_questions">hi</div>
<div class="c_questions">hey</div>
<div class="c_questions">test</div>
<p class="main-body"></p>
by edit into code. (squint suggested.)
if($('.option').hasClass('c_questions')){
var y = document.getElementsByClassName('c_questions');
for(var i = 0; i < y.length; i++){
$('.main-body').append(y[i].innerHTML);
} ^^^^^change
}
Don't use a for loop, look at jQuery's each.
So this would loop through each element with the class example below:
$( ".test" ).each(function( index ) {
console.log($( this ).text() );
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="test">hi</div>
<div class="test">hey</div>
<div class="test">test</div>

Categories

Resources