Should display:none element still have length = 1? - javascript

I'm just wondering if an element with display: none should have a length of 1 in JavaScript. I though display: none was like removing an element from the document and the known universe.
e.g.
$('.element').hide(); // jQuery sets to display: none;
console.log($('element').length); // returns 1

The display:none property is just use to hide the element, it will not remove the element form the DOM.
If you open the console and look into the Elements tab you will still see the element with display:none.
If you want to remove the element then you could use javascript to remove it from DOM.
Example
let elem = document.querySelector(`<css selector>`);
elem.remove();

All that display: none does is it changes the CSS style property of the element. The element still exists in the document, so it's still possible to select it with jQuery or a DOM method. Eg, both
<body>
<div>foo</div>
</body>
and
<body>
<div style="display: none">foo</div>
</body>
exist in the document.
If you want to actually remove the element from the DOM, use .remove() (in both jQuery and built-in JS):
$('.element').remove();
or
document.querySelector('.element').remove();
Both of those will result in the DOM changing from
<body>
<div class="element">foo</div>
</body>
to
<body>
</body>

One more thing is when you use the
$('.element').remove();
or
document.querySelector('.element').remove();
be aware that: The remove() method removes the selected elements, including all text and child nodes.

Related

How add ID to HTML href with javascript

I have an HTML like this
<div class="this">
EXP
</div>
I want to add id to <a>. But do not know what to do.
First select your element using something like .getElementsByClassName(). Keep in mind that .getElementsByClassName() returns a NodeList collection of elements, so you'll want to access the first index (or loop over them). You can then simply set the ID with .id, as the ID is merely a property of an element.
This can be seen in the following:
const element = document.getElementsByClassName('this')[0];
element.id = 'element';
console.log(element);
<div class="this">
EXP
</div>
If you want to add this with Javascript, you'll need to use a selector to target your <a> tag and then set the id attribute on it. You can do this by using the querySelector() function or as seen below:
// Find an <a> tag that occurs below a class called "this" and set its id attribute
document.querySelector('.this > a').id = "some-id";
There are many other available functions to handle this through native Javascript and other frameworks, so your milage may vary depending on what you are using.
Example
In this example, we have provided some CSS that should only apply to an element with an id of "test" and we'll run the necessary code to show that the id is being added to the element (as it will be red):
document.querySelector('.this > a').id = 'test';
#test { color: red; }
<div class="this">
EXP
</div>
Add the id attribute to the <a> tag. See the differences of the middle line:
<div class="this">
<a id="expid" href="exp.com">EXP</a>
</div>

JavaScript: Select an element to a div and update styling

I need to add styling to a DIV element using JavaScript. I have the following DIV in my document:
<div class="RnEpo Yx5HN " role="presentation">
The script that I have tried is:
WebElement = document.querySelectorAll("div[class='RnEpo Yx5HN ']");
WebElement.style='height: 10000px;'
WebElement.setAttribute("height = 1000px;");
I want to achieve the same styling as this CSS:
.RnEpo Yx5HN
{
height: 100000px;
}
To achieve what you require, first replace querySelectorAll() with querySelector() seeing that your only need to select the first matching element.
Consider also revising your selector from div[class='RnEpo Yx5HN '] to a more robust selector in the form of div.RnEpo.Yx5HN which is to say:
Select div elements that have classes any ordering of class RnEpo and Yx5HN
Lastly, revise the way that you're applying the inline style so that the height attribute is directly specified on the WebElement style object.
These changes make the call to setAttribute() redundant. Note also that; setAttribute() takes two arguments, and the DIV element does not have a native height attribute.
Here's a working snippet showing this in action:
/* Use querySelector() to select first matching element and use dot notation syntax to select div with both classes */
const WebElement = document.querySelector("div.RnEpo.Yx5HN");
/* Apply inline style, avoid invalid setAttribute call */
WebElement.style.height = `10000px;'
<div class="RnEpo Yx5HN" role="presentation">

Append element to a div only inside the parentcontainer

How do I append .div4 to .div1 onLy on its parent container without it also appends to the next container with the same div? I tried the basic jQuery appendTo but this sets .div4 on all the .div1 elements in my DOM.
<div class="container">
<div class="div1"></div>
<div class="div2"></div>
<div class="div3"></div>
<div class="div4"></div>
</div>
<div class="container">
<div class="div1"></div>
<div class="div2"></div>
<div class="div3"></div>
</div>
Update: changed invalid HTML. Using this script now (replace dummy divs with my actual divs):
var $this = $('span.conditionHilite.refurbHilite');
$this.appendTo($this.closest('.itembox.centerbox.col.span_1_of_3').find('.image.col1'));
Problem now is that if my page consist of more then one container with"span.conditionHilite.refurbHilite" it will append the total amount of these elements inside each parentcontainer instead of just the one.
If you tried to append an element to more than one target element with jQuery, it will clone that element however many times is required. If you only want to append .div4 to the .div1 element within its same container element, you'll need to explicitly select that element. Something like this:
var $this = $('.div4');
$this.appendTo($this.closest('.container').find('.div1'));
That uses .closest() to traverse up the DOM tree to find the containing element, then .find() to look within that containing element for the .div1 element. With your current DOM structure that will only ever be a single element, so the .div4 element is simply moved, without any clones being created.
Note: As Rory McCrossan pointed out, you're re-using IDs in your HTML and it is therefore invalid. I've used a class selector in the code above on the assumption that you'll fix your invalid HTML by switching from id="container" to class="container". If - as stated in the comments - you absolutely can't change that, then the '[id="container"]' selector should work instead.

Duplicate an element independently of the original

Im trying to duplicate a class and to make it not change when the original is changed. currently I tried
$(".newclass").addClass("oldclass");
which does not copy the content
var _elementClone = $(".oldclass").html();
$(".newclass").html(_elementClone);
this one is good and transfers all the contents of the div
PROBLEM: in all cases when I change the oldclass parent. like
$('.oldclass').hide();
<style>
.oldclass{visibility:collapse}
</style>
the new one also changes.
How can I create new class which does not change when the parent is changed?
You can duplicate the element by getting it's outer HTML, use jQuery to change it's id, class or whatever, and then insert it into the DOM to have independent elements.
EXAMPLE
HTML:
<div id="first" class="top">First Div</div>
<div id="second" class="middle">Second Div</div>
<div id="third" class="middle">Third Div</div>
<div id="last" class="bottom">Last Div</div>
Javascript:
var divs=$(".middle");
$.each(divs,function(i,el) {
var newdiv = $(el.outerHTML);
newdiv.attr("id",newdiv.attr("id")+"-copy");
newdiv.removeClass("middle").addClass("middle-copy");
divs.eq(i).after(newdiv);
});
$("#second-copy").html("copy of second div");
$("#third").html("original third div");
setInterval('$(".middle-copy").toggle()',1000);
Fiddle: http://jsfiddle.net/0cy0gvj9/2/
In the first line you're assigning .newclass to .oldclass. So, when later you hide .oldclass, this selector will include the previous assignment. That is, since all .newclass items are also .oldclass ones, they get hidden as well.
The function you're looking for is .append(), which will append a child to a given element (thus making it a parent).

hide() and show() method when a class selector returns 2 elements

I have a class selector that is returning 2 elements. I did a console.log() and it is an array where 0 is the first and 1 is the second element.
I need to show()/hide() these elements depending on a condition.
I tried doing,
mySelector[0].hide()
mySelector[0].show()
mySelector[1].hide()
mySelector[1].show()
I also tried,
mySelector.first().hide()
mySelector.first().show()
mySelector.last().hide()
mySelector.last().show()
Both approaches did not work. Also, I understood that even css() cant be applied with display: none. What should be my approach to achieve this?
Given the following that matches two elements:
var mySelector = $(".pre.fileContent")
if you want to show (or hide) both:
mySelector.show();
if you want to show (or hide) one of them:
mySelector.eq(n).show();
where n starts from zero.
$("mySelector:eq(0)").hide();
$("mySelector:eq(1)").show();
you can use this
you can use jQuery method with class name.
for eg.
HTML
<div class="mySelector"></div>
<div class="mySelector"></div>
<div class="submit">CLICK</div>
CSS
.mySelector{border:2px dashed green; height:100px; width:100px;}
jQuery
$(".submit").click(function(){
$(".mySelector").toggle();
});
Live fiddle here

Categories