dynamic class select in javascript - javascript

I want to write a function in jquery using handlebars. where name of html and class where it has to be appended will be pass dynamically.
Basically i need something like this :
var pageTemplate="";
function addTempl(){
var renderedPage = pageTemplate(pageName);
$("#Class_id").empty();
$("#Class_id").append( renderedPage );
}
this Class_name and pageName will be dynamically passed to this function from another main function where it will be called.
Issue is i can pass pageName as it is javascript thing but how to do same for Class_name. beacuse if I append '#' and "" it is not coming.
please let me know if my problem is still unclear.

class is denoted by . and id is denoted by #
updated
$("#"+Class_id).empty();
$("#"+Class_id).append( renderedPage );
in one line
$("#"+Class_id).empty().append( renderedPage );

If I understood correctly, you want to use dynamic selector based on passed parameter. You can do something like:
function doSomething(className) {
var selector = "#" + className; // # for id, . for class
$(selector).empty();
$(selector).append(something);
}
Optimized version would be:
function doSomething(className) {
var x = $("#" + className); // # for id, . for class
x.empty();
x.append(something);
}
Optimized = you look for the element in DOM only once

Try this in order to select class use dot .
$("#"+Class_id).empty();
$("#"+Class_id).append( renderedPage );

Related

empty() div + variable

I have to empty a div with an id like this
echo "<td> <div id = \" $ divbouton \ "> \ n";
I pass a variable to a function () like this
function activermedecin(numdiv,statut,nummed) {
var numdiv ;
$("divnum").empty(); // vide la div #
}
My empty () is not working !!
When I put a fixed parameter like this:
$("div_medicin").empty ();
It works
Why ??
Thank you
Stephane
If you are trying to remove a div's property then it should look something like this.
// single element
function removeProperty(selector, property){
document.querySelector(selector).removeAttribute(property);
}
// multiple elements
function removePropertys(selector, property){
document.querySelectorAll(selector).forEach(elm => elm.removeAttribute(property));
}
If you are trying to remove the actual element then it should look like this.
// first match
document.querySelector(cssSelector).remove();
// All matches
document.querySelectorAll(cssSelector).forEach(elm => elm.remove());
If you don't know how to select stuff using css selectors, here's a good cheat sheet: https://devhints.io/css

Making part of an Id name into a variable

I have a bunch of divs with matching ids (#idA_1 and #idB_1, #idA_2 and #idB_2, etc). In jquery I wanted to assign click functions, so that when I click an #idA it will show and hide an #idB.
Basically I want to make this:
$(".idA_x").click(function(){
$("idB_x").toggleClass("hide")
});
X would be a variable to make #idA and #idB match. I could write each individually, but that would take too much code, is there a way to make the number in the id into a variable?
Sure, you can do:
var num = 13;
addButtonListener(num);
function addButtonListener(num){
$("#idA_"+num).click(function(){
$("#idB_"+num).toggleClass("hide")
});
}
Try JQuery solution :
var x = 1;
$(".idA_" + x ).click(function(){
$(".idB_" + x ).toggleClass("hide")
});
Hope this helps.
There are many ways to achieve that, but what you probably want is to create a shared CSS class, e.g. .ids, and bind the event listener to that one:
$('.ids').click(function () {
//...
});
Then you can handle your logic in a cleaner way within the function body.
In order to make it dynamic, and not have to repeat the code for each one of your numbers, I suggest doing as follows:
First, add a class to all the div's you want to be clickable .clickable, and then use the id of the clicked event, replacing A with B in order to select the element you what to toggle the class:
$(".clickable").click(function(){
var id = $(this).attr('id');
$("#" + id.replace('A', 'B')).toggleClass("hide");
});
Or, you can also select all divs and use the contains wildcard:
$("div[id*='idA_']").click(function(){
var id = $(this).attr('id');
$("#" + id.replace('A', 'B')).toggleClass("hide");
});
This solution won't have the need to add a class to all clickable divs.
You can use attribute selector begins with to target the id's you want that have corresponding elements.
https://api.jquery.com/attribute-starts-with-selector/
Then get the value after the understore using split on the id and applying Array.pop() to remove the 1st part of the array.
http://jsfiddle.net/up9h0903/
$("[id^='idA_']").click(function () {
var num = this.id.split("_").pop();
$("#idB_" + num).toggleClass("hide")
});
Using regex would be your other option to strip the number from the id.
http://jsfiddle.net/up9h0903/1/
$("[id^='idA_']").click(function () {
var num = this.id.match(/\d+/g);
$("#idB_" + num).toggleClass("hide")
});

Modify class defined by var on a function

I want to add class "unblock" to all elements contanining desbloquear var value (in this case, taken from clicked a element's id).
I am not able to do this... as there are several ements that should receive the new class, I can not set the same id to them (to be equal as "a" id). How could I say, on the last line of the function, that all items containing "a" class (desbloquear var value) should add class unblock?
I've tried
$(.desbloquear).addClass('unblock');
and
$(".desbloquear").addClass('unblock');
without result...
$('a').on('click', unblock);
function unblock(){
var desbloquear = $(this).attr('id');
$(desbloquear).addClass('unblock');
}
all items containing "a" class (desbloquear var value) should add class unblock
I might not got your question correctly but by above line. It looks that you want to add a class unblock to elements those have some specific class. if yes then you can do like this
function unblock(){
var desbloquear = $(this).attr('class');
$('.'+ desbloquear).addClass('unblock');
}
Yes you are correct, Id's should be unique, you can use class instead
You will need a . to specify a class attribute in selector
$('.'+desbloquear).addClass('unblock');
class selector should begins with a .
Just try,
$('.' + desbloquear).addClass('unblock');
Full code:
$('a').on('click', unblock);
function unblock() {
var desbloquear = $(this).attr('id');
$('.' + desbloquear).addClass('unblock');
}

JQuery to add <body> class, need a little more help

I have this snippet of code to parse the URL and add a class to the <body>tag of my HTML page.
var pathname = window.location.pathname;
var pathSlashesReplaced = pathname.replace(/\//g, " ");
var pathSlashesReplacedNoFirstDash = pathSlashesReplaced.replace(" ","");
var newClass = pathSlashesReplacedNoFirstDash.replace(/(\.[\s\S]+)/ig, "");
$("body").attr("class",newClass);
if ( $("body").attr("class") == "")
{
$("body").addClass("class");
}
The issue I am having is that it deletes existing body classes already there. Instead, I would like to append to whatever body classes exist and not overwrite.
Use this:
$("body").addClass(newClass);
instead of
$("body").attr("class",newClass);
This is a setter: $("body").attr("class",newClass); which sets the class to the newClass and does not append it.
Use addClass instead of attr('class', newClass). The addClass also accepts a white-space separated list of class names, and correctly adds them.
$("body").addClass(newClass);
if ( $("body").attr("class") == "") // Makes no sense, since you have previously
{ // added `newClass`
$("body").addClass("class");
}
For documentation on addClass, see http://api.jquery.com/addClass/
.attr("class", newClass) is removing all existing classes. You should be using .addClass() instead:
$("body").addClass(newClass);
In addition, since you've just added a class to body, the code below will always be false:
if ( $("body").attr("class") == "") { }
Use addClass function instead - http://api.jquery.com/addClass/

How can I add a class to a DOM element in JavaScript?

How do I add a class for the div?
var new_row = document.createElement('div');
This answer was written/accepted a long time ago. Since then better, more comprehensive answers with examples have been submitted. You can find them by scrolling down. Below is the original accepted answer preserved for posterity.
new_row.className = "aClassName";
Here's more information on MDN: className
Use the .classList.add() method:
const element = document.querySelector('div.foo');
element.classList.add('bar');
console.log(element.className);
<div class="foo"></div>
This method is better than overwriting the className property, because it doesn't remove other classes and doesn't add the class if the element already has it.
You can also toggle or remove classes using element.classList (see the MDN documentation).
Here is working source code using a function approach.
<html>
<head>
<style>
.news{padding:10px; margin-top:2px;background-color:red;color:#fff;}
</style>
</head>
<body>
<div id="dd"></div>
<script>
(function(){
var countup = this;
var newNode = document.createElement('div');
newNode.className = 'textNode news content';
newNode.innerHTML = 'this created div contains a class while created!!!';
document.getElementById('dd').appendChild(newNode);
})();
</script>
</body>
</html>
3 ways to add a class to a DOM element in JavaScript
There are multiple ways of doing this. I will show you three ways to add classes and clarify some benefits of each way.
You can use any given method to add a class to your element, another way to check for, change or remove them.
The className way - Simple way to add a single or multiple classes and remove or change all classes.
The classList way - The way to manipulate classes; add, change or remove a single or multiple classes at the same time. They can easily be changed at any time in your code.
The DOM way - When writing code according to the DOM model, this gives a cleaner code and functions similar to the className way.
The className way
This is the simple way, storing all classes in a string. The string can easily be changed or appended.
// Create a div and add a class
var new_row = document.createElement("div");
new_row.className = "aClassName";
// Add another class. A space ' ' separates class names
new_row.className = "aClassName anotherClass";
// Another way of appending classes
new_row.className = new_row.className + " yetAClass";
If an element has a single class, checking for it is simple:
// Checking an element with a single class
new_row.className == "aClassName" ;
if ( new_row.className == "aClassName" )
// true
Removing all classes or changing them is very easy
// Changing all classes
new_row.className = "newClass";
// Removing all classes
new_row.className = "";
Searching for or removing a single class when multiple classes are used is difficult. You need to split the className string into an array, search them through one by one, remove the one you need and add all others back to your element. The classList way addresses this problem and can be used even if the class was set the className way.
The classList way
It is easy to manipulate classes when you need to. You can add, remove or check for them as you wish! It can be used with single or multiple classes.
// Create a div and add a class
var new_row = document.createElement("div");
new_row.classList.add( "aClassName" );
// Add another class
new_row.classList.add( "anotherClass" );
// Add multiple classes
new_row.classList.add( "yetAClass", "moreClasses", "anyClass" );
// Check for a class
if ( new_row.classList.contains( "anotherClass" ) )
// true
// Remove a class or multiple classes
new_row.classList.remove( "anyClass" );
new_row.classList.remove( "yetAClass", "moreClasses" );
// Replace a class
new_row.classList.replace( "anotherClass", "newClass" );
// Toggle a class - add it if it does not exist or remove it if it exists
new_row.classList.toggle( "visible" );
Removing all classes or changing to a single class is easier done the className way.
The DOM way
If you write code the DOM way, this looks cleaner and stores classes in a string by setting the class attribute.
// Create a div, add it to the documet and set class
var new_row = document.createElement( "div" );
document.body.appendChild( new_row );
new_row.setAttribute( "class", "aClassName anotherClass" );
// Add some text
new_row.appendChild( document.createTextNode( "Some text" ) );
// Remove all classes
new_row.removeAttribute( "class" );
Checking for a class is simple, when a single class is being used
// Checking when a single class is used
if ( new_row.hasAttribute( "class" )
&& new_row.getAttribute( "class" ) == "anotherClass" )
// true
Checking for or removing a single class when multiple classes are used uses the same approach as the className way. But the classList way is easier to accomplish this and can be used, even if you set it the DOM way.
If doing a lot of element creations, you can create your own basic createElementWithClass function.
function createElementWithClass(type, className) {
const element = document.createElement(type);
element.className = className
return element;
}
Very basic I know, but being able to call the following is less cluttering.
const myDiv = createElementWithClass('div', 'some-class')
as opposed to a lot of
const element1 = document.createElement('div');
element.className = 'a-class-name'
over and over.
If you want to create multiple elements all with in one method.
function createElement(el, options, listen = [], appendTo){
let element = document.createElement(el);
Object.keys(options).forEach(function (k){
element[k] = options[k];
});
if(listen.length > 0){
listen.forEach(function(l){
element.addEventListener(l.event, l.f);
});
}
appendTo.append(element);
}
let main = document.getElementById('addHere');
createElement('button', {id: 'myBtn', className: 'btn btn-primary', textContent: 'Add Alert'}, [{
event: 'click',
f: function(){
createElement('div', {className: 'alert alert-success mt-2', textContent: 'Working' }, [], main);
}
}], main);
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap#4.6.0/dist/css/bootstrap.min.css" integrity="sha384-B0vP5xmATw1+K9KRQjQERJvTumQW0nPEzvF6L/Z6nronJ3oUOFUFpCjEUQouq2+l" crossorigin="anonymous">
<div id="addHere" class="text-center mt-2"></div>
var newItem = document.createElement('div');
newItem.style = ('background-color:red');
newItem.className = ('new_class');
newItem.innerHTML = ('<img src="./profitly_files/TimCover1_bigger.jpg" width=50 height=50> some long text with ticker $DDSSD');
var list = document.getElementById('x-auto-1');
list.insertBefore(newItem, list.childNodes[0]);
Cross-browser solution
Note: The classList property is not supported in Internet Explorer 9. The following code will work in all browsers:
function addClass(id,classname) {
var element, name, arr;
element = document.getElementById(id);
arr = element.className.split(" ");
if (arr.indexOf(classname) == -1) { // check if class is already added
element.className += " " + classname;
}
}
addClass('div1','show')
Source: how to js add class
var new_row = document.createElement('div');
new_row.setAttribute("class", "YOUR_CLASS");
This will work ;-)
source
It is also worth taking a look at:
var el = document.getElementById('hello');
if(el) {
el.className += el.className ? ' someClass' : 'someClass';
}
If you want to create a new input field with for example file type:
// Create a new Input with type file and id='file-input'
var newFileInput = document.createElement('input');
// The new input file will have type 'file'
newFileInput.type = "file";
// The new input file will have class="w-95 mb-1" (width - 95%, margin-bottom: .25rem)
newFileInput.className = "w-95 mb-1"
The output will be: <input type="file" class="w-95 mb-1">
If you want to create a nested tag using JavaScript, the simplest way is with innerHtml:
var tag = document.createElement("li");
tag.innerHTML = '<span class="toggle">Jan</span>';
The output will be:
<li>
<span class="toggle">Jan</span>
</li>
<script>
document.getElementById('add-Box').addEventListener('click', function (event) {
let itemParent = document.getElementById('box-Parent');
let newItem = document.createElement('li');
newItem.className = 'box';
itemParent.appendChild(newItem);
})
</script>

Categories