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

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>

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 do I get child elements from class list object?

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

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>

Sort divs by ID in JavaScript

I'm trying to sort divs by ID in Javascript. So far, I've got an array of divs split into "leftSlide" and "rightSlide". I'm doing it like so:
var leftSlides = [];
var rightSlides = [];
$(".ms-left").find("div").each(function(){ leftSlides.push(this.id); });
$(".ms-right").find("div").each(function(){ rightSlides.push(this.id); });
And my console output is:
// Left Divs
["slide0", "slide1", "slide2", "slide3", "slide4", "slide5", "slide6", "slide7", "slide8", "slide9", "slide10"]
// Right Divs
["slide-right0", "", "slide-right1", "", "slide-right2", "", "slide-right3", "", "slide-right4", "", "slide-right5", "", "slide-right6", "", "slide-right7", "", "slide-right8", "", "slide-right9", "", "slide-right10", ""]
Now I want to re-order my divs so they go something like this:
<div id="slide0"></div>
<div id="slide-right0"></div>
<div id="slide1"></div>
<div id="slide-right1"></div>
<div id="slide2"></div>
<div id="slide-right2"></div>
...and so on.
I notice that there's an errant empty div in the "slide-right" divs, but it's probably ok for them to be ignored, and if not, I'll try to find some logic to not add them to the array if they're empty. For now just trying to sort properly.
Any tips?
Assuming your slides will always have the same length on the left side and the right side and are ordered correctly you can use this code.
Please specify if you could have any other case!
var leftSlides = [];
var rightSlides = [];
$(".ms-left").find("div[id]").each(function(){ leftSlides.push(this); });
$(".ms-right").find("div[id]").each(function(){ rightSlides.push(this); });
$all = $(".all");
for (var i=0; i<leftSlides.length; i++) {
$all.append(leftSlides[i]);
$all.append(rightSlides[i]);
}
This code selects only divswith an id and then iterates trough the leftSlides array and pushes the elements from both arrays into one, first left then right.
jsBin demo
if you remove "-right" from "slide-right0" you'll get the matching pair "slide0":
$(".ms-right").find("div").prop("id", function(i, id){
$("#"+ id.replace("-right","")).after( this );
}).end().remove(); // After all is moved remove the .ms-right element.
div{
padding:5px; margin:5px;
background:rgba(255,0,0,0.2);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="ms-left">
<div id="slide0">0</div>
<div id="slide1">1</div>
<div id="slide2">2</div>
<div id="slide3">3</div>
<div id="slide4">4</div>
<div id="slide13">13</div>
</div>
<div class="ms-right">
<div id="slide-right0">r0</div>
<div>no ID</div>
<div id="slide-right1">r1</div>
<div>no ID</div>
<div id="slide-right2">r2</div>
<div>no ID</div>
<div id="slide-right3">r3</div>
<div>no ID</div>
<div id="slide-right4">r4</div>
<div>no ID</div>
<div id="slide-right13">r13</div>
</div>
I have't try this code, just give you a tip.
var leftSlides = [];
var rightSlides = [];
$(".ms-left").find("div").each(function(){ leftSlides.push(this.id); });
$(".ms-right").find("div").each(function(){ rightSlides.push(this.id); });
$('#yourNewWrapper').html(function(){
var allLeft = $('.ms-left').find('div');
var allRight = $('.ms-right').find('div');
var longLength = allLeft.length > allRight.length ? allLeft.length : allRight.length;
var divHtmlCache = [];
for(var i = 0; i < longLength; i++){
var eachLeft = allLeft.eq(i).length ? allLeft.eq(i) : null;
var eachRight = allRight.eq(i).length ? allRight(i) : null;
divHtmlCache.push(eachLeft ? eachLeft.html() : '' );
divHtmlCache.push(eachRight ? eachRight.html() : '');
}
return divHtmlCache.join('');
});
You may try. I did not use any special function except for $.insertBefore for moving the elements as needed.
for(var x=0; x < $('div').length; x++)
{
for(var i=0; i < $('div').length; i++)
{
if((i+1) < $('div').length)
CompareDivs( $('div')[i], $('div')[i+1]);
}
}
function CompareDivs(curr,next)
{
var curr_idNum = $(curr).attr("id").substring($(curr).attr("id").length - 1,$(curr).attr("id").length);
var next_idNum = $(next).attr("id").substring($(next).attr("id").length - 1,$(next).attr("id").length);
if(curr_idNum > next_idNum)
{
$(next).insertBefore($(curr));
}
}
Working example : https://jsfiddle.net/DinoMyte/3h78pjkh/1/
You could try something like this:
var leftSlides = [];
var rightSlides = [];
$(".ms-left").find("div").each(function(){ leftSlides.push(this); });
$(".ms-right").find("div").each(function(){ rightSlides.push(this); });
$all = $(".all");
for (var i=0; i<leftSlides.length; i++) {
$all.append(leftSlides[i]);
$all.append(rightSlides[i*2]);
}
https://jsfiddle.net/edoLtp1h/

Categories

Resources