Add id to dynamically created DIV - javascript

I would like to add an ID to the div with the class name="leaflet-control-layers-base". Because this HTML script is automatically generated through an API (Leaflet) when the page is loaded, I cannot add the id within the script.
The reason I am asking is because I have two of these scripts as shown below within my page. I would like to distinct them from each other so that I can refer to them individually. The only difference is that the other script is not located in the "TOCContent" div.
Any ideas how I can add an id using JavaScript or jQuery to the 'leaflet-control-layers-base' class?
Here is my script:
<div id="TOCContent">
<div class="leaflet-control-layers leaflet-control-layers-expanded" aria-haspopup="true">
<form class="leaflet-control-layers-list">
<div class="leaflet-control-layers-base">
</form>
</div>

Try this:
$(".leaflet-control-layers-base").attr("id","your id will go here");

Select the element using the combinator selector, to ensure it selects a descendant of #TOCContent, then set the id property.
$('#TOCContent .leaflet-control-layers-base').prop('id', 'someid');
Remember to run this after your API code has rendered the elements on the page, not before. You will probably need to hook up to some sort of complete event on your API, because the basic DOM Ready event will likely fire before the API has rendered the elements.
Side note: it may not be necessary to give the element an ID, since by doing so you need to obtain a reference to the element anyway, which you can store in a variable.
var base = $('#TOCContent .leaflet-control-layers-base');

Related

Chrome extension to automatically replace html code

How could I change the value of id automatically,
e.g. if I have
<div id = "email">
I would like to change it to
<div id = "nick">?
AutoReplaceHTML seems to be what you are looking for. If you would like further customization, you can use content scripts with JavaScript that searches for elements by id.
I'm not sure why you would want to do this, however. The id of an element is used to determine which CSS styles apply to it and can possibly be used in scripts (like the JavaScript getElementById() example I linked). Changing the id of an element could break the styling or produce an error in any of the attached scripts.

Binding jQuery .on event to dynamic button with dynamic id

I have a situation where I need to bind an onclick event to a button which is being dynamically injected into the main html document by an external JavaScript.
The problem is that that the class id of the button is suffixed with some dynamic numbers which change every time the page is reloaded.
Please see example:
<button class="clickme12345" type=submit value=clickme>send</button>
Now the situation is that on every page reload the numbers for the class id for the button will change so next time it will be clickme67890.
Would there be any way to get the jQuery binding to work for this situation?
Any reply would be greatly appreciated.
If this is really how you want to use it, you could use an attribute selector
Something like [attr*=value] where the attr contains the string value.
For example (in jQuery):
var $btnElement = $('[class*="clickme"]');
The above will select any elements that have a class attribute containing clickme

Using Jquery to control dymanically generated HTML

What I've got is a web page containing a DIV into which I'm dynamically putting a list of entries with selector buttons, I've simplified the code a lot for this example
The target DIV looks like
<div id="targetdiv"></div>
I ask a server for a list and build a string that looks something like
<div>
nameofentryfromserver1
<input type="button" class="dynamicbutton" onclick="someroutine('nameofentryfromserver1')">
</div>
<div>
nameofentryfromserver2
<input type="button" class="dynamicbutton" onclick="someroutine('nameofentryfromserver2')">
</div>
<div> ... same thing for next entry and so on
Then I insert this into the document with
$( "#targetdiv").html( generatedstring );
Now this works fine and I get a nice list and when I click on the generated button the correct routine is started and the parameter is passed correctly and I get the results I expect.
However when the button is pressed I would like to disable all the "dynamicbutton" class elements, re enabling them once processing is complete.
Inside the routine I call I have the line
$( ".dynamicbutton").attr( "disabled", "disabled");
But this doesn't seem to affect any of the dynamically generated content, if I have other buttons on the page belonging to the same class they get disabled though, so it looks like I can only access content from the originally loaded document using this method.
I've even tried giving each button a unique id and referencing each one individually with no success.
So is there a way of generating this content so that jQuery can access it via it's normal element selection, or is there some other technique I need to usein order to manipulate them ?
You need to run the code AFTER you have added the dynamic content to the page. If you run the code before, jQuery doesn't see the dynamic content. I would run the code when the user presses a button then again after the dynamic content is added. Then remove it after you are done processing.
Also you can use $( ".dynamicbutton").prop( "disabled", true);
It seems if I use a class that hasn't been used for selection previously, then I can use it to select my dynamically generated group.
So if I generate an indeterminate number of inputs with class="brandspankinnewelements" and that class hasn't been used previously as a selector for any other elements on the page
I can now select that group with $( ".brandspankinnewelements" )
That makes life a lot simpler.
How about this?
Insert the script after the #targetdiv and try if it will work.
The .dynamicbutton from here will only disable all the class dynamicbutton inside the id targetdiv.
<div id="targetdiv"></div>
<script type='text/javascript'>
$('.dynamicbutton').click( function() {
$('#targetdiv .dynamicbutton').attr("disabled", "disabled");
});
</script>
You need to delegate the events for such case as the element is not available in the DOM when the event is bound to the #target
Also it is preferable to use .prop() instead of .attr()
Try this
$('body').on('click', '#targetdiv', function() {
$(".dynamicbutton").prop( "disabled", true);
});

Jquery doesn't apply hide() to all of the divs with the same ID

I'm making a site, and the html is displayed through php with data fetched from a database.
I have a foreach() function, so all of the things displayed have the same DIV ID's.
It ends up being like 4 DIVs with the same ID (#content), so the PHP works fine, but I have a jQuery script and when I call the jQuery("#content").hide(); it only hides ONE of the DIV's not all of them, and I want it to hide all of them. Is there something else I have to do?
Thanks.
You should use a class (.class_name), not an id--only one DOM element may have a given ID, otherwise it's invalid HTML. It's reasonable for an ID selector to return only a single element.
IDs on elements on a page should be unique. So every HTML tag you specify should have a different ID. If you want to hide all of a certain element, it might be suitable to add a class to the elements you wish to hide?
e.g.
<div class="divToHide">Content...</div>
<div class="divToHide">Content...</div>
<div class="divToHide">Content...</div>
Then your jquery would be:
$(".divToHide").hide();
That's simply because you cannot have more than one element with a specified ID. IDs are and must be unique. Only one single element with the same element may exist in a DOM.
Failing to follow this rule may result in broken scripts and other horrors.
You can use classes for this purpose.
an ID can only be used ONCE in HTML! because its a id and a id should always be Unique

How can I apply prototype's toggle to content loaded via JSON, IE problem only

I use PHP and javascript via prototype.
i have a threaded comments page that on open
by default via javascript call to a PHP file data returned via JSON, only parent comments are retrieved in the db. (in short only parent comments are fetched from db and displayed)
then the parents are loaded and formatted to be shown on the page with a link to get and display its child comments, link example:
<span id="moreparent8351" onclick="insertChildDiv('parent8351')">1 Replies and more</span>
the span link above calls the javascript function "insertChildDiv()" that basically gets comments whose parent_id=parent8351, also using a PHP file that returns data via JSON to the javascript that dynamically inserts this child comments nested under its parent comment.
then the span link above using prototype transforms into:
<span id="moreparent8351" onclick="$('childparent8351').toggle()">1 Replies and more</span>
now here is the problem, this inserted content inside this div with id=childparent8351 wont respond to the hide/show toggle ONLY in IE v6,v7 and v8. other browsers work fine.
it looks like IE cannot apply the hide/show toggle to a dynamically inserted content.
I tried hardcoding the inserted content that i see in fogbugz to the page and testing it again on IE, guess what? toggle works!
I dont want to fetch all the comments both parent and child and then hide the child comments, that is a waste of resources on something that we are not sure is important or to be read by the users.
Is there a workaround? if there is none, then i hope this post will help others on their design stage for something similar.
Element.toggle() should work fine with dynamically generated content. Your problem most likely lies within the method you use to generate this content.
You stated:
then the span link above using
prototype transforms into:
<span id="moreparent8351" onclick="$('childparent8351').toggle()">1 Replies and more</span>
How exactly are you changing the onclick attribute of the span element?
First of all, I definately would not recommend changing an onclick event on-the-fly. It is probably better to use one function that checks the current state of what you are trying to do and executes the appropriate code.
Be sure not to "transform" your span element, including the onclick attribute using innerHTML. Chances are the DOM is still trying to reference a function that you have just removed. If updating your onclick attribute at all, do it like this:
var element = $('moreparent8351');
// this automatically removes previous onclick handlers set in this manner
element.onclick = function() { // do stuff };
...or, when you want to it the Prototype way:
var element = $('moreparent8351');
// OPTIONAL: remove previous handler, if set
element.stopObserving('click', my_cool_function());
// attach new handler
element.observe('click', function() { // do stuff });

Categories