javascript - select a div within a particular div - javascript

The content of the divs is going to be populated with javascript json. Now, I know how to select a div in javascript:
var hsc = document.getElementByID("hsc");
But how would I refer to eg. the title but only in the hsc div.
<div id="hsc">
<div id="title"></div>
<div id="jobs"></div>
...
</div>
<div id="cc">
<div id="title"></div
<div id="jobs"></div>
</div>
On a separate note, wouldn't 'title' and 'jobs' be better classified as classes, and not ids?

This would work:
var hsc = document.querySelectorAll("#hsc > .title");
But you need to change to valid html and use unique IDs and classes instead:
<div id="hsc">
<div class="title"></div>
<div class="jobs"></div>
...
</div>
<div id="cc">
<div class="title"></div>
<div class="jobs"></div>
</div>

IDs must be unique in HTML.
Change them to classes, and then you can use querySelector() to target them:
document.querySelector('.hsc .title').style.color= 'blue';
document.querySelector('.cc .title').style.color= 'red';
<div class="hsc">
<div class="title">Make me blue!</div>
<div class="jobs">Jobs</div>
</div>
<div class="cc">
<div class="title">Make me red!</div>
<div class="jobs">More jobs</div>
</div>

Just try
<div id="hsc">
<div id="a" class="title"></div>
<div id="b" class="jobs"></div>
...
</div>
<div id="cc">
<div id="c" class="title"></div
<div id="d"class="jobs"></div>
</div>
Because your HTML code is invalid because the id is already taken.

Related

Could I get to an element using two ids?

Here's my code:
<div id='layer1'>
<div id='a'>
<div id='b'>
<div id='layer2'>
<div id='a'>
<div id='b'>
<div id='layer3'>
<div id='a'>
<div id='b'>
I want to try to get the element [a] of layer1.
Could I do this using pure javascript and withOUT jquery and other stuff?
An ID uniquely identifies one single element on the page. The behavior you described is more like "a class" inside of an ID:
document.querySelector("#counter-for-drinks .up-arrow")
and so if you want a different up-arrow, it is:
document.querySelector("#counter-for-burgers .up-arrow")
document.querySelector() is what is similar to jQuery $(" "). It also has the form document.querySelectorAll() for getting all matched elements.
Your HTML is missing closing tags. You can always validate your code here.
Also, you should use class instead of id.
<div id='layer1'>
<div class='a'></div>
<div class='b'></div>
</div>
<div id='layer2'>
<div class='a'></div>
<div class='b'></div>
</div>
<div id='layer3'>
<div class='a'></div>
<div class='b'></div>
</div>
You can use javascript to get elements:
document.querySelector("#layer1 .a")
var firstA = document.querySelectorAll('#layer1 #a');
var nodeString = '';
if (firstA.length > 0) {
for (var i = 0; i < firstA.length; i++) {
nodeString = nodeString + firstA[i].innerText + '<br/>';
}
}
document.getElementById('founded-nodes').innerHTML = nodeString;
#founded-nodes {
color: brown;
}
<div id='layer1'>
<div id='a'>layer1 aaa</div>
<div id='b'>layer1 bbb</div>
</div>
<div id='layer2'>
<div id='a'>layer2 aaa</div>
<div id='b'>layer2 bbb</div>
</div>
<div id='layer3'>
<div id='a'>layer3 aaa</div>
<div id='b'>layer3 bbb</div>
</div>
<div id="founded-nodes"></div>
As all said in above over comments and answers, one must use a single id on the same page, or else the use of classes is a must. But if you want to achieve this, you can have a look at code.

How to get the attribute value of the closest element

Here i have HTML structure and the same structure may repeat number of times with the same class names. what i'm trying to do is once i click on the .innerDiv i should be able to access the attr value of the .inid close to its parent element.
here is what i have tried, but its not working. i also tried adding the classname to the element i'm trying to get the value from. but its adding the class to all the element with .inid. how can i do this?
HTML
<div class="parent_div">
<div class="content-container">
<div class="second-most-innerdiv>
<div class="container-box">
<div class="innerDiv">Click here</div>
</div>
</div>
</div>
<div class="inid" data-attr="jkoadoas-Kjksjfks_skaj"></div>
</div>
<div class="parent_div">
<div class="content-container">
<div class="second-most-innerdiv>
<div class="container-box">
<div class="innerDiv">Click here</div>
</div>
</div>
</div>
<div class="inid" data-attr="jkoadoas-Kjksjfks_skaj"></div>
</div>
Jquery
$(this).on('click',function(){
$('.innerDiv').parents().find('.inid').addClass('testclass');
$('.innerDiv').parents().find('.inid').attr(data-attr);
});
To achieve expected result, use index of innerDiv and add class-testclass to element with class- inid
Find index of clicked innerDiv using index('.innerDiv)
Use that index to add class using eq
Add some sample css to testclass for testing
Syntax error in your code - closing quotes missing for class- second-most-innerdiv
Codepen - https://codepen.io/nagasai/pen/
working example
$('.innerDiv').on('click',function(){
$('.inid').eq($(this).index('.innerDiv')).addClass('testclass');
console.log($('.inid').eq($(this).index('.innerDiv')).attr('data-attr'))
});
.testclass{
background: red;
height: 10px;
width:10px
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="parent_div">
<div class="content-container">
<div class="second-most-innerdiv">
<div class="container-box">
<div class="innerDiv">Click here</div>
</div>
</div>
</div>
<div class="inid" data-attr="jkoadoas-Kjksjfks_skaj"></div>
</div>
<div class="parent_div">
<div class="content-container">
<div class="second-most-innerdiv>
<div class="container-box">
<div class="innerDiv">Click here</div>
</div>
</div>
</div>
<div class="inid" data-attr="jkoadoas-Kjksjfks_skaj"></div>
</div>
Using JQuery closest() feature to find the parent div, then find the element with class "inid" within that parent element and get the value of the attribute.
$('.innerDiv').on('click',function(){
var inid = $(this).closest('.parent_div').find('.inid');
inid.addClass('testclass');
console.log('selected -> ' + inid.attr(data-attr));
});
Source: https://api.jquery.com/closest/

How do I find each child that comes after the body element, and get the html of the element with a certain class within it

That might sound a little confusing, but basically I have some html that looks like this (which is dynamically created)
<body>
<div class="component" id="465a496s5498">
<div class="a-container">
<div class="random-div">
<div class="wantThis">
<div class="wantThisHTML">Hello!<p>I'm another element!</p></div>
</div>
</div>
<div class="random-div">
<div class="random"></div>
</div>
</div>
</div>
<div class="component" id="683fg5865448">
<div class="another-container">
<div class="random-div">
<div class="wantThis">
<div class="wantThisHTML">Wow!</div>
</div>
</div>
<div class="random-div6">
<div class="random2"></div>
</div>
</div>
</div>
<div class="component" id="247487294js5">
<div class="more-containers">
<div class="random-div">
<div class="wantThis">
<div class="wantThisHTML">Haha!</div>
</div>
</div>
<div class="random-div6">
<div class="random5"></div>
</div>
</div>
</div>
</body>
And I want to create an array of objects which includes the unique id of the component and the raw HTML within the element with class name "wantThis" (it will always be called "wantThis"), so the array would look like
[{
id: "465a496s5498",
html: "<div class='wantThisHTML'>Hello!<p>I'm another element!</p></div>"
},{
id: "683fg5865448",
html: "<div class='wantThisHTML'>Wow!</div>"
},{
id: "247487294js5",
html: "<div class='wantThisHTML'>Haha!</div>"
}]
As for what i've tried, I split up the elements into an array using var elements = $(body).children, and I know to get the HTML within an element using $(.wantThis).html(), but how can I get the id and the HTML from each of the elements I obtain from the children?
Also, within the wantThis element there may me multiple elements, will $(.wantThis).html() get the raw HTML of ALL the children?
There you go.
var data = $('> .component', document.body).map(function(component) {
return {
id: this.id,
html: $(this).find('.wantThisHTML').html()
}
})
.toArray();
console.log(data);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="component" id="465a496s5498">
<div class="a-container">
<div class="random-div">
<div class="wantThis">
<div class="wantThisHTML">Hello!
<p>I'm another element!</p>
</div>
</div>
</div>
<div class="random-div">
<div class="random"></div>
</div>
</div>
</div>
<div class="component" id="683fg5865448">
<div class="another-container">
<div class="random-div">
<div class="wantThis">
<div class="wantThisHTML">Wow!</div>
</div>
</div>
<div class="random-div6">
<div class="random2"></div>
</div>
</div>
</div>
<div class="component" id="247487294js5">
<div class="more-containers">
<div class="random-div">
<div class="wantThis">
<div class="wantThisHTML">Haha!</div>
</div>
</div>
<div class="random-div6">
<div class="random5"></div>
</div>
</div>
</div>
ONE approach to this is....
Select the Nodes (elements) using "querySelectorAll"
let nodeListOfComponentElements = document.querySelectorAll('.component')
This will get you a NodeList. NodeList
You can turn that into an array of Nodes by:
let nodeArray = [].slice.call(nodeListOfComponentElements) SO-Post
Then, using that array of nodes. You can 'map' it to the structure you want.
let result = nodeArray.map(function(item, index) {
let targetElement = item.querySelector('.wantThisHTML')
return {
id: item.id,
html: targetElement.innerHTML
}
})
note: each "item" is an element/node and the method querySelector can be used to select children of that element. I'm targeting the class you mentioned. Then it's just a matter of returning an object for each iteration that the map function executes. You pick the keys and values that the map function returns. Here I'm setting the id key to the id of the element, and the html key to the "innerHTML" of the target child element within each main element.
The resulting structure is as follows:
(3) [{…}, {…}, {…}]
0: {id: "465a496s5498", html: "Hello!<p>I'm another element!</p>"}
1: {id: "683fg5865448", html: "Wow!"}
2: {id: "247487294js5", html: "Haha!"}
length: 3
CodePen: https://codepen.io/nstanard/pen/exOJLw
Don't forget to upvote and approve my answer it helps!
Thanks
To make sure the .component has wanted '.wantThis' child.
var data = $('.wantThis').map(function() {
return {
id: $(this).parents('.component').attr('id'),
html: $(this).html()
}
});
console.log(data);
var data = $('.wantThis').map(function() {
return {
id: $(this).parents('.component').attr('id'),
html: $(this).html()
}
});
console.log(data);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="component" id="465a496s5498">
<div class="a-container">
<div class="random-div">
<div class="wantThis">
<div class="wantThisHTML">Hello!<p>I'm another element!</p></div>
</div>
</div>
<div class="random-div">
<div class="random"></div>
</div>
</div>
</div>
<div class="component" id="683fg5865448">
<div class="another-container">
<div class="random-div">
<div class="wantThis">
<div class="wantThisHTML">Wow!</div>
</div>
</div>
<div class="random-div6">
<div class="random2"></div>
</div>
</div>
</div>
<div class="component" id="247487294js5">
<div class="more-containers">
<div class="random-div">
<div class="wantThis">
<div class="wantThisHTML">Haha!</div>
</div>
</div>
<div class="random-div6">
<div class="random5"></div>
</div>
</div>
</div>
<div id="elem">
<div id="elem-content">Element</div>
</div>
<script>
alert(elem); // DOM-element with id="elem"
alert(window.elem); // accessing global variable like this also works
// for elem-content things are a bit more complex
// that has a dash inside, so it can't be a variable name
alert(window['elem-content']); // ...but accessible using square brackets [...]
</script>
reference: https://javascript.info/searching-elements-dom

jQuery select closest child element by class

How would I use jQuery to get get the text from the rating selected div within the id=overall answer div?
I want to dynamically fetch the text "TESTING" from that div within the overall parent div.
<div class='answer' id="overall">
<div class='rating'>1</div>
<div class='rating'>2</div>
<div class='rating'>3</div>
<div class='rating'>4</div>
<div class='rating selected'>TESTING</div>
</div>
<div class='answer' id="effort">
<div class='rating'>1</div>
<div class='rating'>2</div>
<div class='rating'>3</div>
<div class='rating selected'>4</div>
<div class='rating'>TESTING</div>
</div>
I tried to do this and it is blank.
$(document.getElementById('overall')).find('.rating selected').text();
Your code would work but your selector is wrong. It would be...
$(document.getElementById('overall')).find('.rating.selected').text();
Notice the dot and no space between rating and selected.
However, I think you are over complicating things...
$('#overall .selected').text();
Example...
alert($('#overall .selected').text());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<div class='answer' id="overall">
<div class='rating'>1</div>
<div class='rating'>2</div>
<div class='rating'>3</div>
<div class='rating'>4</div>
<div class='rating selected'>TESTING - selected</div>
</div>
<div class='answer' id="effort">
<div class='rating'>1</div>
<div class='rating'>2</div>
<div class='rating'>3</div>
<div class='rating selected'>4</div>
<div class='rating'>TESTING - not selected</div>
</div>
$('#overall .rating.selected').html()

duplicate a div with children

I need to clone a div with its children, I know the clone() function in jQuery, but I need to change the style of the parent div, or change the id name or show the whole div by animate, is there any way to do this?
This is the div I need to clone and I need to change the top attribute
<div class="news">
<div class="meta-inform">
<div id="waiting">not accepted</div>
<div id="accpted">accepted</div>
<div class="edit">
<div class="editedBy" id="editedBy" >
<div id="editLabel" style="display:inline">edited by</div>
<div id="editorName" style="display:inline">arvin</div>
</div>
<div id="editTime" class="editTime">
<div id="editDate" style="display:inline" >چdate</div>
<div id="editDate" style="display:inline">time</div>
</div>
</div>
</div>
<div id="littleNews">
<div id="number">1000</div>
<div id="divider1"></div>
<div id="title">title</div>
<div id="divider2"></div>
<div id="littleNewsTime">time</div>
<div id="littleNewsDate">چdate</div>
<div id="divider3"></div>
<div id="category">cat</div>
<div id="part">part</div>
<div id="segment">sgmnt</div>
<div id="divider4"></div>
<div id="writer">writer</div>
<div id="view">view post</div>
</div>
<div class="functions">
<div id="edit">edit</div>
<div id="delete">delete</div>
<div id="accptThis">accept</div>
</div>
</div>
Use clone to clone the div with its children.
Use the attr function to change attributes.
Use the css function to change css attributes.
e.g.:
$('.news').clone().attr("id","whatever").css("width","50px")
Then for example, you can append it to any other container you want.
e.g.:
$('.news').clone().attr("id","whatever").appendTo($('body'));
You can also use addClass or removeClass to add/remove classes defined in your CSS files.
does that help?
You could just add new class name and then add proper styles into css, for example:
$('.news').clone().addClass("clone");
And to the css sheet:
.clone {
top: 100px;
}
$('.news').clone().attr("id","elementid").appendTo("body").animate({ 'top': '200px'}, 2000);

Categories

Resources