Exclude multiple elements from a DOM query using a variable - javascript

I have this HTML:
<div class="elem">
</div>
<div class="elem-1">
</div>
<div class="elem-2">
</div>
<!--Select the ones below-->
<div>
</div>
<p class="other-class">
</p>
I have this code:
var elems = document.querySelectorAll(".elem, .elem-1, .elem-2[,...]");
var otherElems = document.querySelectorAll(":not..."); //can I reuse elems here?
Can I use the elems variable to select all elements except for the ones in elems?
EDIT: This seems like code duplication:
var foos1 = document.querySelectorAll(".bars1, .bars2, .bars3, #bar1, #bar2[,...]");
var foos2 = document.querySelectorAll(".bars-1, .bars-2, .bars-3, #bar-1[,...]");
var foos3 = ...
.
.
.
var foosN
//list all former elements again
var noFoos = document.querySelectorAll(":not(.bars1, ..., .bars-3, #bar-1......)");
Instead I would like to reuse the variables I stored these elements in already.
Something like:
var noFoos = document.querySelectorAllBut(foos1, foos2, foos3,...);

You could put the first selector inside the not:
var elements = document.querySelectorAll(".elems, .elems-more, .elems-more-more[,...]");
var otherElements = querySelectorAll("div:not(.elems, .elems-more, .elems-more-more[,...])");
Also, you could put the selector in a variable to avoid duplication. This might not be the most efficient solution, though.

Related

change label foreach element in html using javascript

I am using both html and velocity and came up with this code. The names and images are stored in an array and this is the code I used to display each of the contents of this array to the page.
#foreach($starter in $starter)
<div class="product">
<div class="color"><img src= "$starter.img" width="100" height="100"></div>
<span class="product-name">$starter.name</span>
<div class="compare-wrap">
<input type="checkbox" id="">
<label id="view">Compare</label>
</div>
</div>
#end
I wanted the label to change from "Compare" to "View Compare" while at the same time storing its id in the array upon checking their correspondng check box. I eventually came up with this code:
var checkedArray = [];
$(":checkbox").change(function(){
if((this).checked){
checkedArray.push(this.id);
document.getElementById('view').innerHTML = "<a href='/compare'>View Compare</a>";
}
else{
checkedArray.splice(checkedArray.indexOf(this.id), 1);
document.getElementById('view').innerHTML = 'Compare';
}
var str = checkedArray.join(', ');
alert(str);
});
but it seems it is only applicable to the first content of the array. Any idea how I can use a foreach code at this point?
document.getElementById() only supports one name at a time and only returns a single node not an array of nodes. You should use a class:
var views = document.getElementsByClassName('view');
var i = views.length;
while(i--) {
views[i].innerHTML = "Compare";
}
HTML
<label class="view">Compare</label>
Element ID must be unique.
Hope it helps.

How to detect element with DOM JavaScript?

I want to detect an element and change the backgroundColor through JavaScript but am having trouble with it.
I can't check for the element because it is a tag+class + tag+class...
Here's my code :
var one = document.getElementsByTagName("div");
var two = document.getElementsByClassName("red");
var three = document.getElementsByTagName("h2");
var four = document.getElementsByClassName("title");
one.two three.four.style.backgroundColor ="#00c497";
The format is "div.red h2.title".
How can I correctly detect an element using DOM JavaScript?
If you can, use querySelector for this:
document.querySelector("div.red h2.title").style.backgroundColor = "#00c497";
<div>
<h2>Don't Touch</h2>
</div>
<div class="red">
<h2>Don't Touch</h2>
<h2 class="title">Change</h2>
</div>

Get id from string using javascript

I have this simple string:
<div id="parent">
<div id="1" class="child">test</div>
</div>
How can I extract the id number (1) from this string?
With JQuery you can
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
var str = $('<div id="parent"><div id="1" class="child">test</div></div>');
console.log(str.find(':nth-child(1)').attr('id'));
</script>
Where nth-child is the target you want to get the id
var s = '<div id="parent"> <div id="1" class="child">test</div> </div>';
var d = new DOMParser().parseFromString( s, "text/xml" );
var id = d.firstChild.childNodes[1].attributes['id'];
console.log( id );
var htmlString = '<div id="parent"><div id="1" class="child">test</div></div>';
var number = /id="(\d)"/.exec(htmlString)[1];
console.log(number); //outputs the number
You would have to do a match on the string object that the HTML is stored in. so, if the string is called htmlString, then you would do something akin to
var id = htmlString.match(/id=\"([0-9]+)\"/)
That SHOULD net you the result, but if you deal with any data that is more complex than the example you've been given, you would need a different regex.
<script>
let num = document.getElementById('1')
let ans = parseInt(num.id)
</script>
Although I am unsure as to what you are trying to accomplish, one way of getting of doing this is s to gather all like tagnames ("div" in this case) into an array and select the array index you desire (1 in this case) then reference the id - as follows:
var list=document.getElementsByTagName("div")
alert(list[1].id);

how to remove the lastchild element of dynamically generated DIV and return the html as string

How to remove the lastchild of the dynamically generated div and regenerate the html as string.
Sample HTML DIV
strHtmlString = "<div contenteditable='true' id='undefined'>Test1</div>
<div contenteditable='true' id='sentenceFreeTextField67' type='sentenceFreeTextField'>One</div>
<div id='multiselectAnchors' type='multi'>
<div id='options32' >Two</div>
<div contenteditable='true' id='sentenceFreeTextField68' type='sentenceFreeTextField'>One</div>
</div>
<div id='blank4' contenteditable='true' type='blankField'> </div>
<div id='Div1' type='multi'>
<div id='options33' >Three</div>
<div contenteditable='true' id='sentenceFreeTextField69' type='sentenceFreeTextField'>One</div>
</div>"
here is the code sample
if (($('<DIV/>').html(strSentence)[0].lastChild.lastChild.type === 'sentenceFreeTextField') && (!$.trim($('<DIV/>').html(strSentence)[0].lastChild.lastChild.innerText))) {
strHtmlString = $('<DIV/>').html(strSentence)[0].lastChild.lastChild.remove().html; (this remove().html doesn't work)
}
the need is to delete the lastchild of the div at runtime and convert back to string as it was earlier. I can do string manipulation however, might not the be the right way, please suggest
var el = $(strHtmlString);
// dont know what you meant by last child, so taking the id
el.children().find("#sentenceFreeTextField69").remove();
var str = el.wrap("<div/>").parent().html()
Generate a DIV dynamically:
$('body').append('<div>');
Access the DIV immediately after generation:
var $divElement = $('body').append('<div>').find('div');
Get the last child:
var $lastChildElement = $divElement.last();
Get the HTML of the last child (more specifically, the innerHTML):
var $lastChildHTML = $lastChildElement.html();
Do it all together then you turn around:
var $lastChildHTML = $('body').append('<div>').find('div').last().html();
That's what it's all about.
var last = $(element).children(':last-child');
var html = $(last).html();
$(last).remove();
var newHtml = $(element).html();
//incase you want the html with it's parent as well do this
var newHtml = $(element).parent().html();

Javascript: Get div inside of div

I have two divs nested like so:
<div id="upper">
<div id="lower" name="moo">
</div>
</div>
How would I, using jQuery or JavaScript alone, can I get the name of that lower nested div?
var nameValue = $('#lower').attr('name');
But if you really want to use the outer div to select the inner one:
var nameValue = $('#upper > div').attr('name');
Or
var nameValue = $('#upper #lower').attr('name');
Or
var nameValue = $('#upper').find('#lower').attr('name');
Use .children.
http://api.jquery.com/children/

Categories

Resources