JQuery: adding attributes of Elements that appended - javascript

i tried to access the attribute of an element that appended to an element that it appended too.
".chat-private" appended too.
how can i do this?
this is my script code:
$('#users-list').on('click', '.chat-private', function () {
$("#dialog-area").append("<div class='dialog'><h4>Chat</h4><textarea cols='30' rows='10' id='chatarea'></textarea><input type='text' id='chattext'></div>");
var userid = $(this).attr("userid");
$('#dialog').attr('userid', userid);
});
and HTML:
<div id="users-list">
users:
</div>
<div id="dialogs-area">
</div>

Your div has a class dialog and in selector you are saying #dialog. You should say .dialog.
$('#dialog').attr('userid', userid);
DEMO
And you should avoid adding custom attributes to elements, use data-attributes inroduced in HTML5.

Add id's to your html strings. When you append the code, you can then reference them later by id to manipulate them. Just be careful - chicken before the egg and what not.
http://jsfiddle.net/qrggj2go/
<div id="test"/>
$("#test").append("<button id='test2'>Hi</button>");
$("#test2").click(function(){
$("#test2").hide();
});

Related

Javascript: How to print input to <div> selected by class?

Edit: Thanks for the helpful answers so far! I'm still struggling to print the input to the "right" div, though. What am I missing?
Next to the input field, there is an option to select either "left" or "right". Depending on the selection, the input is to be printed eiether left or right on the click of a button. This is what I have - but it only prints to the left, no matter the selection.
jQuery(document).ready(function(){
$('.button').click(function(){
$('.input').val();
if ($('select').val() == "left"){
$('div.left').html($('.input').val());
}
else {
$('div.right').html($('.input').val());
}
});
});
</script>
Sorry if this is very basic - I am completely new to JS and jQuery.
I'm trying to print input from a form into a div. This is part of the source HTML modify (it's for a university class):
<input type="text" class="input">
<div class="left">
</div>
<div class="right">
</div>
Basically, text is entered into the field, and I need to print this text either to the "left" or the "right" div when a button is clicked.
So far, I have only ever dealt with divs that had IDs, so I used
document.getElementById("divId").innerHTML = ($('.input').val());
But what do I do now when I don't have an ID? Unfortunately, changes to the HTML source are not an option.
Thanks in advance!
Just use normal selectors, like css and jQuery does.
https://api.jquery.com/category/selectors/
in your case:
$('div.left').html($('.input').val());
As you see there are many ways to do this. You can get elements by tag name, class, id...
But the most powerful way is to get it with querySelector
function save() {
var input = document.querySelector('input').value;
document.querySelector('div.left').innerHTML = input;
}
<input type="text" class="input">
<button onclick="save()">Save</button>
<div class="left"></div>
<div class="right"></div>
There are plenty of other ways to target HTML elements, but the one you're looking for in this case is getElementsByTagName(). Note that this returns a NodeList collection of elements, so you'll additionally need to specify the index that you wish to target (starting at 0). For example, if you want to target the second <div> element, you can use document.getElementsByTagName("div")[1].
This can be seen in the following example:
let input = document.getElementsByTagName("input")[0];
let button = document.getElementsByTagName("button")[0];
let div2 = document.getElementsByTagName("div")[1];
button.addEventListener("click", function(){
div2.innerHTML = input.value;
});
<input type="text">
<button>Output</button>
<br /><br />
<div>Output:</div>
<div></div>
Since you have unique class names for each element, document.getElementsByClassName can be used. This will return an array of elements containing the class. Since you only have one element with each class name, the first element of the returned array will be your target.
<input type="text" class="input">
<button onclick="save()">Save</button>
<div class="left"></div>
<div class="right"></div>
<script>
function save() {
var input = document.getElementsByClassName('input')[0].value;
document.getElementsByClassName('left')[0].innerHTML = input;
}
</script>
This is one of the many ways to do what you want:-
Write the following in console:
document.getElementsByTagName("div");
now you can see the total number of div elements used in your current document/page.
You can select one of your choice to work on by using "index number"(as in array index) for that particular div.
Lets say your div having class name = "right" is the 3rd one among the other div elements in your document.
This will be used to access that div element.
document.getElementsByTagName("right")[2].innerHTML = "whatever you want to write";

Why isn't this jQuery selector finding anything?

I have a div inside a div. This inner div has a data attribute. I tried to apply the answer from this question to find the inner div, but am having no luck. What am I doing wrong?
var content = $('#mapElements').find('.mapMarker [data-depotid="b04b4184"]').data('depotguid');
$('#result').text(content);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='mapElements'>
<div class="mapMarker" data-depotid="b04b4184">This is the text from mapMarker, and if the depotID appears below this text the code works!</div>
</div>
<div id='result'></div>
Wrong Selector for targeting .mapMarker element. Use:
var content = $('#mapElements').find('.mapMarker[data-depotid="b04b4184"]').data('depotguid');
//^space not required here
You can also narrow down the selector for child element to:
var content = $('#mapElements').find('.mapMarker').data('depotguid');
Try this
$(" #mapElements > .mapMarker[data-depotid='b04b4184'] ");
or directly
$(".mapMarker [data-depotid='b04b4184']");

How to append just before the end of the BODY tag using JQuery [duplicate]

I have this HTML:
<div class="region-list" id="region_North_America">
<strong>North America</strong>
</div>
and want to add more divs after the strong element to result:
<div class="region-list" id="region_North_America">
<strong>North America</strong>
<div> ... </div>
<div> ... </div>
<div> ... </div>
</div>
I am trying this:
var row_str = '<div>content here</div>';
$('#region_North_America div:last').html(row_str);
However, there is no change to the html. This is probably so since there is no div within the element selected.
I know that the js is making it to this code because I can print the content of row_str to the console.
So, how can I get to the end of that container element to add the new items?
Thx.
Try:
$("#region_North_America").append(row_str);
using append().
Or:
$("<div>content here</div>").appendTo("#region_North_America");
To create the element on the fly, and place it in the document.
Using the appendTo method.
Your code will just place html in the last div within #region_North_America. Use the append function.
$("div.region-list").append(row_str);

tag next to a label in javascript

I do not have the luxury of using jQuery, I want to hide the span tag in certain conditions using Javascript and the span tag does not have an id.
"<label name="lcity" id="lcity" for="city" class="formLabel" title="City">City:</label>
<span class=spanclass>*</span>
I tried something like this and did not work:
var countyFieldLabel = document.getElementById('lcity').nextElementSibling;
countyFieldLabel.visibility="hidden";
Can anyone suggest something please?
Thanks
You almost go it right:-
Visibility is not an element attribute instead it is a style attribute.
use
countyFieldLabel.style.visibility="hidden";
Instead of
countyFieldLabel.visibility="hidden";
Fiddle
Use nextSibling instead of nextElementSibling:
function hideSpan()
{
var element = document.getElementById("lcity").nextSibling.style.visibility = 'hidden';
}
HTML:
<body onload="hideSpan()">
<label id="lcity" for="city" class="formLabel" title="City">City:</label><span class=spanclass>*</span>
</body>
In Addition, please remove your name attribute in label. It is not allowed.

Is it possible to append to a div with a given attribute?

How do you append to a specific div with a specified attribute?
ex.
<div attribute="234"></div>
$('#divwithattribute234').append('test');
jQuery('div[attribute=234]').html('test');
Check on jsfiddle
I strongly recommend reading this post about using custom attributes because that wouldn't be valid even in HTML5 which will allow custom attributes. Why not simply use a class since you can have as many as you want ?
<div class"some_class some_other_class target_class"></div>
Of all the above classes, assuming 'target_class' is the one used for identifying the <div>, you would select it and append to it with
$(".target_class").html('test');
Update:
If you have more than one target <div>s and you're looking for a specific one, use a wildcard selector on the trigger (in our case we'll use the ^= operator which means 'starts with') and then assign its ID to a variable which we then pass to the <div> selector. Say you want to add your text to a div when a link is clicked ...
HTML
Add to DIV 1<br />
Add to DIV 2<br />
Add to DIV 3<br />
<div class="some_other_class target_1">Div 1</div>
<div class="some_other_class target_1">Div 2</div>
<div class="some_other_class target_1">Div 3</div>
jQuery
$("a[id^=target_div_]").click(function(event) {
var targetID = $(this).attr('id').substr(11);
$("div.target_" + targetID).html('content got inserted in div ' + targetID);
event.preventDefault();
});
See it on JSFiddle.
Hope this helps !
This is how you will match your div (<div attribute="234"></div>):
$("div[attribute=234]").html('Lets write something...');

Categories