Changing the ID of html elements - javascript

I have a form which allows user to add elements(which might be a field set or a text box) dynamically. I'm able to assign a new ID to the elements when added but I'm not able to make it in a sequence as the user can add elements in between as well.
So for example, there is an Id named XXX1 and the user adds a new element after it which is xxx2. Now if the user adds a new element again after XXX1, it comes up as XXX3. So the order of the elements is XXX1, XXX3, XXX2. I'm not able to control the names when it is being added. So I'm trying to re-assign the names after add.
I'm trying to get all elements in an array and change the ID as follows
document.getElementById('xxx3').setAttribute('id', 'xxx2');
But this doesn't work as ID XXX2 already exists for another element. Please help me with a solution for this.

So why not change the ID of xxx2 first, to move it out of the way, then putting it back in place later?
document.getElementById('xxx2').setAttribute('id', 'temporaryId');
document.getElementById('xxx3').setAttribute('id', 'xxx2');
document.getElementById('temporaryId').setAttribute('id', 'xxx3');

Why not go from the last element to the first(the one's after the position you are inserting to) and add one to the ID?
for example:
var insertAt = 2; // for an element to be called xxx2
var els = [...]; // an array with all of the elements
if(els.length >= insertAt){
for(var i = els.length-1; i >= insertAt-1; --i){
els[i].setAttribute('id', 'xxx'+(i+2));
}
}
// Add the new element here which will be called xxx2

Related

jQuery .not() doesn't remove element?

I am grabbing a copy of some info from a page, but I do not want to include certain <option> elements that appear inside <select> elements on the page.
Therefore, while I grab all the elements I want and am storing them in the variable fields, I check to see if each element is a <select> and if they have the specific <option> that I don't want.
var field = allFields[i].innerHTML; //allFields is the raw HTML I'm iterating through
if ($(field).find("select").length > 0) { //If the element we're looking at contains a select
console.log("Found a select. It is in " + field);
console.log($(field).find(".bad-option");
field = $(field).not(".bad-option").prop("outerHTML"); //Use .not() to remove the elements which have the .bad-option class
// (and .prop("outerHTML") is just there to convert it back to a String instead of a jQuery object)
}
console.log("Adding " + field);
fields[i] = field; //Add the HTML, free of any unwanted options, to the `fields` variable
Based on jQuery's documentation, I would expect the .not() function to remove any elements out of field which have the bad-option class. Yet that is not the case at all. When I log field before and after using .not(), it prints out the same thing. See the console output from the code above:
Found a select. It is in <label>Description: <select><option>thing1</option><option class="bad-option">thing2</option></select></label>
-----------------
[jQuery list object size 1, containing an object called option.bad-option]
-----------------
Adding <label>Description: <select><option>thing1</option><option class="bad-option">thing2</option></select></label>
So what's going on? How do I remove an option with a certain class from from within a jQuery object? Why isn't .not() working?
If I need to clarify anything, please let me know. I tried to make this question as specific as possible and would be happy to elaborate on any details further.
The documentation is perhaps a bit confusing: not removes elements from the selection, not the DOM. If you want to remove the elements, then just filter and remove:
const processed = $(field);
processed.filter(".bad-option").remove();
field = processed.prop("outerHTML");

jQuery: How can I get the class of a certain element that's inside another element?

Lets say I have a table named unitTables with some rows. It is one of many similar tables on the webpage. In those rows is a class called selected, which I want to retrieve for a variable. The other tables on the page also use the selected class, so I need to retrieve this specific instance of selected.
In plain JavaScript, the way to find it is:
var table = document.getElementById('unitTables');
var selected = table.getElementsByClassName("selected");
What's the equivalent to the above two rows in jQuery?
I know I can rewrite the first row like this:
var table = $('#unitTables');
But I know I can't do the exact same thing to the next row, as I need to use to id of unitTables in order to get the specific selected row in that table. Currently I have:
var selected = from.$(".selected");
Which throws an Uncaught TypeError: from.$ is not a function. error, so I know that's not the correct syntax.
What's the best approach?
var table = document.getElementById('unitTables');
var selected = table.getElementsByClassName("selected");
What's the equivalent to the above two rows in jQuery?
var selected = $("#unitTables .selected");
(Except selected will be a jQuery object around the matched set of elements, instead of a collection.)
The jQuery function (jQuery or [usually] $) looks up elements via CSS selectors. So in this case, a descendant selector that looks for .selected within #unitTables.

How do I display a unique id value with GTM?

I have multiple elements on a page with the same class name, but each element has a unique id name.
Example:
<div class="video-image" id="get-googled">
<div class="video-image" id="email-marketing">
I want to display the id value, but right now I am only able to have GTM return and display the first element on the page. I read this post: "Getting value of ID from class" and it didn't help and even explains doing it the simple way will only display the first elements value.
Do I need custom Javascript to create this properly?
If you want to get a specific div and you know where it is on the page you might be able to use a DOM variable with an nth of type query selector. But this seems cumbersome, and since it seems you want a list in any case I think you are better of with a custom javascript variable:
function() {
return document.querySelectorAll(".video-image");
}
which return a collection of DOM elements (you might want to check if there are actually elements with that class first).
The initial answer is the right start - this completes the loop:
<script>
var inputs = document.querySelectorAll(".video-image");
for (var i = 0; i < inputs.length; i++) {
alert(inputs[i].id);
}
</script>
Here is a JSFiddle to try it out - [https://jsfiddle.net/JMurphy22/kduybmsp/2/][1]

Going to specific instance of element class

I can use the following to create a indexed list of each instance of a particular item in a class.
var x = document.getElementsByClassName("page");
I can use the following to direct users to a particular id:
function CalledBySelectBox(value)
{
document.getElementById(value).scrollIntoView();
}
However, the elements I want to direct users to are not uniquely identified with Id's. How do I modify the second snippet above, to direct users to a particular instance/occurrence of x in the first snippet. Or to put it differently, how do I direct them to a particular instance of the class.
If its helpful, here is some sample html:
Some text of unknown length full of random tags and what have you.<span class="page">104</span> A bunch more text but we don't know how much and full of other tags.<span class="page">105</span> Some text of unknown length full of random tags and what have you <span class="page">106</span>
I think you are looking for something like this:
function ScrollToPage( page_num )
{
document.getElementsByClassName( 'page' )[ page_num ].scrollIntoView();
}
What getElementsByClassName(className) gives you is an array of elements, what document.getElementById(id) gives you is a single element. To scroll to an indexed element in the array you get, just call scrollIntoView() on that element.
var x = document.getElementsByClassName("page");
x[5].scrollIntoView();

how to access the elements which created using the jquery insertAfter method

i have a select tag which when its change I'm showing another input for the user and when the user change the select tag multiple times the element insert after each other but i want to remove old input after changing the select tag and insert the new related input.
Just keep track of a reference to the element then...
var element;
$("#sel").change(function () {
var sel = $(this);
if(element)//check if an input has already been created
element.remove();//remove the old input from the DOM
element = $("<input/>").val(sel.val());//create the new input and store the reference
element.insertAfter(sel);//insert the new input to the DOM
});
$("#sel").change();
Here is a working example
Because insertAfter is a function of the element you are creating, you must already be creating a reference to it in your current code anyway. So you just need to store that reference globally. Then each time you change the select, you can check if the reference has a value and remove it from the DOM.
Put the new elements in a selectable div or span, and empty the container before creating the new element:
$('#inputContainer').empty().append('<input/>');

Categories

Resources