This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Change an element's CSS class with JavaScript
Found lot of topics about this topic, but none helped me. I have:
<div id="text-6" class="block col-228">
Javascript code should add new class fit, so result should be:
<div id="text-6" class="block col-228 fit">
How to do that with javascript?
Try like this:
var elem = document.getElementById("text-6");
elem.setAttribute("class", elem.getAttribute("class")+" fit");
Important note: You need to be assure,that your DOM Hierarchy is constructed completely,then try to manipulate DOM Elements. That is why you need to put DOM manipulation scripts inside of the window.onload callback, or if you use jQuery, then inside of $(document).ready callback.
You put the following between your script tags.
document.getElementById('text-6').className += " fit";
I'd recommend using jQuery. Then you can just do something like this:
$("#text-6").addClass("fit");
EDIT:
Including the whole jQuery library may be overkill for your situation, but if you're dealing with DOM manipulation a lot, jQuery can simplify things quite a bit. If it's just for this one thing, then some of the other answers provided would be better.
Related
This question already has answers here:
How to append/prepend/create a text node with jQuery
(3 answers)
Closed 6 years ago.
I'm creating a JavaScript framework to build HTML documents. First a virtual document is built using jQuery. Right now, I'm experimenting with jQuery's "add" function like so:
$(target).append($("").add($("<div>")).add($("<span>")))
The framework concatenates these calls to build the virtual document before it is appended to the target - this simplified code sample isn't literally what I'm doing. The reason for adding the first $("") is because the framework starts by creating an empty jQuery selection then adds stuff to it. Sub-documents are recursively created and added to parent elements.
This works fine for concatenating elements together, but what if I want to concatenate text? Let's say I want to have something like this rendered:
<div></div> Outside the box!
I can't just do $("<div>").add("Outside the box!") Also, $.after() doesn't seem to work unless the <div> is already on the DOM.
Is this functionality supported by jQuery? If not, are there any workarounds?
Yes, you can use simple string concatenation with current HTML of element: $('<div>').html($('<div>').html() + 'Outside the box!')
Since your code DOM is in memory and not actual HTML, you need to use multi-line code:
var $div = $('<div>', {html: $('<div>')});
$div.html($div.html() + "Outside the box!");
This question already has answers here:
How to dynamically create CSS class in JavaScript and apply?
(17 answers)
Closed 6 years ago.
I have a series of divs that share a class for assorted reasons (and a number of divs that get created via code at other points).
I've tried to find answers, but all rely on the class being in the stylesheet (if there even is one), which is something that doesn't happen in this case or that alters existing elements instead of the rules themselves.
So I need to do something like...
var add_to_styles('myClassName');
myClassName.cssText = "color: red;"
And have all divs that get created (both before and after the script running) that have the class
<div class="myClassName">I should be red</div>
To come out with the rule change. But I haven't found anything like this.
You can add new <style></style> with new rules (new or existing classes) and append it to body (so it will be read after other stylesheets).
You can also target by specific parent (and don't modify other existing elements if you don't want to change all of them).
If you are using jQuery you can try to use .css() function.
https://jsfiddle.net/rixlabs/annt81df/1/
for some tests
$(".myClassName").css("color", "red");
Try this one:
document.getElementByClassName('myClassName').style.color = "red";
or
document.getElementById('myIdName').style.color = "red";
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
If I have many following divs:
<div class="error"> </div>
<div class="error"> </div>
<div class="error"> </div>
<div class="error"> </div>
<div class="error"> </div>
...
What is the best way (and best practice) to hide them all at once?
$('.error').hide() or
.addClass('hide') including .hide { display: none; } ?
Best is an opinion, you can run jsperf tests and each browser will be different.
In the end you will either loop in JavaScript and add classes or set style attributes or just rely on the CSS to do the looping for you.
Look at using a selector
$(".error").hide(); // or .addClass() or .css("display","none")
Under the covers it does:
a DOM lookup for one or more elements
it is doing a for loop over the set
it gets the current element in the loop iteration
Applys a css rule in the loop iteration
Ends up doing a redraw/repaint
But one way to not have to loop is to just rely on adding a CSS rule higher up in the hierarchy.
CSS:
.hideErrors div.error {
display: none;
}
JavaScript:
$(document.body).addClass("hideErrors");
What this does:
DOM lookup for one element
Adds one class
Ends up doing a redraw/repaint
This way you do not have to loop through and add a class to every element. It would be better to place the "hideError" rule around the element that wraps the error list. So change "body" to that parent element.
It really doesn't matter which you pick. If it's that important to you, run a benchmark.
Most of the browser's time would be handling layout and repaint anyway, the addition of class or inline style (Because that's what .hide() does, add style="display: none; to the element) really doesn't matter either way.
If you care about performance, drop jQuery, start using some vanilla JS, learn about page performance and optimize your JavaScript and CSS selectors.
Honestly, how you modify the DOM is the last thing you should be worrying about :)
The term best isn't really enough information, because it can mean performance (speed) or size (included libraries).
If you already are using JQuery, it is generally a very efficient library and the following is how you would do that after the DOM finished loading.
$( document ).ready(function() {
$('.error').hide()
});
There are other events besides 'DOM ready' that JQuery defines that you can hook the action up to, which is why its a convenient library.
If you are just interested in overall speed and want to avoid external libraries, CSS is generally your fastest way to go, and you would add the class as you stated in your Style Sheet. This limits when you can hide them to before the DOM loads.
There are best and worst cases for all of the situations you described. Javascript will have to loop (parse) through the DOM so it will always be slower than pure CSS.
I think add and remove class will be better way to handle this.
In this way you can also do other styling changes related to error message.
css code :
.showdiv {
display : block;
}
.hidediv {
display:none;
}
javascript code :
$('.error').addClass('showdiv')
$('.error').removeClass('hidediv')
If you would like them hidden on page load add a class hidden to the divs.
.hidden{
display: none;
}
To show and hide just use jquery.
$('.error').hide();
$('.error').show();
This question already has answers here:
jQuery OR Selector?
(6 answers)
Closed 9 years ago.
I am working on an ASP.NET page in which I generate some JavaScript code based on values in a database.
For example, in the database there might be the formula sum([#itemA]), which would evaluate to something like $('#itemA').change(function(){ sum(this); });.
I know that I can select elements using jQuery selectors such as $('[id*=itemA]') or $('[class*=itemA]'), but I am wondering if there is any way to combine these selectors so that any element with either a class or an ID of itemA would be selected.
Right now in my code I am just using if/else blocks to deal with ID's or classes, but if there is an easier implementation, I would love to use it.
I looked at the jQuery documentation and googled around a bit, but I didn't see anything that answered my question.
Thanks in advance!
This should do the trick
$('[id*=itemA], [class*=itemA]')
For more details, take a look to official jquery documentation
Use multiple selectors like
$('.class1, .class2....., .classn')
You can literally use anything like ID names, class names or selectors like you specified separated by commas
Like in css, when selectors are separated by ,they are cumulated :
var elements = $('[id*=itemA], [class*=itemA]')
This question already has answers here:
jQuery : remove element except inside element
(4 answers)
Closed 8 years ago.
There is a great method in jquery called wrap() that will wrap a selected element inside a new element, like so:
Start with:
<p>I wish I was wrapped!</p>
Add code:
$("p").wrap("<div></div>");
End with:
<div><p>I wish I was wrapped!</p></div>
But what I need is something that will unwrap, so that the above process is reversed. It seems that the issue is that when you select a bad item (let's say an unnecessary table) that it always grabs what is inside it as well, so if I want to remove all <td>s, I am left with nothing, since that removed the td and anything inside.
Is there a standard reliable way of removing elements but leaving any children/ancestors alone?
In JQuery 1.4 unwrap() was added:
http://api.jquery.com/unwrap/
A quick Google search reveals that there is such functionality, in the form of a small 576 byte plugin called jqueryunwrap. I have not tried it personally, but it is worth a shot. ;)
$("p").unwrap() will unwrap the wrapping div....................I hope this helps