I have a html like follows.
<tr class="meta-info" id="${page.id}">
<td>
<div class="pull-left">
<font size="1">
Like
</font>
</div>
<div class="pull-right" style="font-size:1">
<span class="badge"><i class="icon-thumbs-up"></i>1</span>
</div>
</td>
</tr>
I am trying to increase the number of likes when ever the user cliks on Like hyperlink.
Here is my jquery code. I want to know how i can get the html element from the jquery object.
$(".like").click(function(event){
var parentTr = $(event.target).closest("tr");
if(parentTr.length){
var pageId = parentTr.attr("id");
var spanEle = parentTr.get(0)+" div span:first-child"; ------(1)
var lastNumber = parseInt(spanEle.text());
spanEle.text(lastNumber+1);
}
});
I don't know if i am doing right on line which is marked 1.
I think you need to add an extra <span> tag so that you can replace the count without touching the adjacent icon
<span class="badge"><i class="icon-thumbs-up"></i>
<span class="like-count">1</span>
</span>
then you can address it
$(".like").click(function() {
var spanEle = $(this).closest('tr').find('.like-count').first();
if (spanEle.length) {
var newCount = parseInt(spanEle.text());
spanEle.text(newCount + 1);
}
});
In an event handler, the this reference is event.target. You may be able to handle the element doesn't exist case neater than that too but that way's safe.
JSFiddle demo: http://jsfiddle.net/rupw/VfCvK/
Try this...
$(".like").click(function(event) {
var parentTr = $(event.target).closest("tr");
if (parentTr.length) {
var pageId = parentTr.attr("id");
var spanEle = parentTr.first('.badge');
var lastNumber = parseInt(spanEle.text(), 10);
spanEle.text(lastNumber + 1);
}
});
If the span element always has that classname then it will find the first (only?) one and return an int value of the text within.
Try: Fiddle
var lastNumber = parseInt(parentTr.find('.pull-right span').text(), 10);
You code will look like:
$(".like").click(function(event) {
var parentTr = $(event.target).closest("tr");
if (parentTr.length) {
var pageId = parentTr.attr("id");
var spanEle = parentTr.find('.pull-right span');
var lastNumber = parseInt(spanEle.text(), 10);
spanEle.text(lastNumber + 1);
}
});
Update: If you wish to keep the <i> tag then use:
spanEle.html(spanEle.html().replace(lastNumber, lastNumber + 1));
insteadof : spanEle.text(lastNumber + 1);
Sample
Related
JavaScript name change of cloned input element "terminal0" isn't saving and/or reverting back to original name after function ends. All other name/id changes work but first element name change reverts back after function completes. Even the first element "terminal0" id change works successfully. I've tested and confirmed name change does work before function exits by placing an alert(cTerm.name) at the end of it. Anyone know reason why name change isn't working for first input element?
<tr id="tr1">
<td id="tr1Td0">
Terminal <input type="checkbox" name="terminal0" id="terminal0" value="0" onClick="cbUpdate()">
<br>
Imager <input type="checkbox" name="imager0" id="imager0" value="0" onClick="cbUpdate()">
</td>
</tr>
</tbody>
</table>
function addTable()
{
var gssTable = document.getElementById("gssTable");
var currTables = gssTable.rows[0].cells.length;
var selNum = document.getElementById("sNum").value;
var tr0 = document.getElementById("tr0");
var tr1 = document.getElementById("tr1");
var br = document.createElement('br');
for(x=currTables; x < selNum; x++)
{
var tr0Td0 = tr0.insertCell(-1);
var setID0 = document.getElementById("setID0");
var cSetID = setID0.cloneNode(true);
cSetID.id = "setID" + x;
cSetID.name = "setID" + x;
tr0Td0.appendChild(cSetID);
var tr1Td0 = tr1.insertCell(-1);
tr1Td0.innerHTML="Terminal";
var terminal0 = document.getElementById("terminal0");
var cTerm = terminal0.cloneNode(true);
cTerm.id = "test" + x;
cTerm.name = "test" + x;
tr1Td0.appendChild(cTerm);
tr1Td0.appendChild(br);
tr1Td0.innerHTML = tr1Td0.innerHTML + "Imager"
var imager0 = document.getElementById("imager0");
var cImager = imager0.cloneNode(true);
cImager.id = "imager" + x;
cImager.name = "imager" + x;
tr1Td0.appendChild(cImager);
}
while (currTables > selNum)
{
tr1.deleteCell(-1);
tr0.deleteCell(-1);
currTables = currTables - 1;
}
Setting the innerHTML makes the browser re-render that element and its contents. Since you are doing it each iteration of the loop, you are probably causing a race condition where innerHTML hasn't been updated to the latest effects of the appendChild calls above it.
So instead of setting innerHTML each time you can just create a Text node, with createTextNode, and append it.
tr1Td0.appendChild(document.createTextNode("Imager"));
http://jsfiddle.net/rfnslyr/CRqXm/1/
I have the following fiddle which extracts CSS classes and ID's, and posts them to console. I want to type a name into the top box, paste some code, and have it generate a separate set of unique css ID's and classes into a new instance of the #classes instance (which has uin0CE + a bunch of classes in it).
I have that posting to console done, I just don't know how to "spawn" a new instance of the the #classes section on submit every time I add a new name to #codeName and code to #codeInput.
index.html
<div id="container">
<input id="codeName" class="boxsizingBorder"></input><br>
<textarea id="codeInput" class="boxsizingBorder"></textarea><br>
<button id="submitCode">submit</button>
<div id="classes">
<div class="pageTitle">uin0CE</div>
<div class="cssClassesIDs">
ui-icon-nodisc,redDotClass,translate,test,ui-hide-label,ui-grid-a,ui-block-a,ui-block-b,alignRight,ui-grid-solo,ui-disabled,companyFieldset,longbutton,icon-map-marker,locationIcon,icon-phone,contactIcon,legalBlock,legal,legalDivider,signInInfoIcon,icon-info-sign,ui-icon-alt
</div>
</div>
</div>
<script src="functions.js"></script>
functions.js
$(function() {
$('#submitCode').click(function() {
var CSS_CLASSES = [];
var CSS_IDS = [];
var el = document.createElement( 'div' );
var text = $("#codeInput").val();
el.innerHTML = text;
var nodes = el.getElementsByTagName('*');
for (var i = 0; i < nodes.length; i++) {
var node = nodes[i];
if (node.id.length > 0) {
CSS_IDS.push.apply(CSS_IDS, node.id.split(" "));
}
if (node.className.length > 0) {
CSS_CLASSES.push.apply(CSS_CLASSES, node.className.split(" "));
}
}
var uniqueNames = [];
$.each (CSS_CLASSES, function(i, el){
if($.inArray(el, uniqueNames) === -1) uniqueNames.push(el);
});
console.log(uniqueNames + " --- " + uniqueNames.length);
});
});
Edit: I added this to your fiddle:
//Added this section here
var name = $('#codeName').val();
var code = uniqueNames;
$('#classes').empty();
$('#classes').append('<div class="pageTitle">'+name+'</div>');
$('#classes').append('<div class="cssClassesIDs">'+code+'</div>');
Here's the updated fiddle: http://jsfiddle.net/CRqXm/4/
I'm hoping I'm following your question correctly, but this seems to be what you're looking for.
I have output from a CMS where I need to add a style to a certain character in the string. For instance, my output is:
<div class="date">12 // 14 // 2013</div>
How can I add:
<span style="slashColor">
to the two double slashes so that my result would be:
<div class="date">12 <span class="slashColor">//</span> 14 <span class="slashColor">//</span> 2013</div>
Try this:
var original = $('.date').text();
var new_version = original.split('//').join('<span class="slashColor">//</span>');
$('.date').html(new_version);
Fiddle
If you have many div like the example you posted, you can use this:
$('.date').each(function () {
var original = $(this).text();
var new_version = original.split('//').join('<span class="slashColor">//</span>');
$(this).html(new_version)
});
Fiddle
var elements = document.getElementsByClassName('date');
for (var i = 0, e; e = elements[i++]; ) {
e.innerHTML = e.innerHTML.replace(/\/\//g, '<span class="slashColor">//</span>');
}
or the jQuery way:
$('.date').each(function () {
$(this).html($(this).html().replace(/\/\//g, '<span class="slashColor">//</span>'));
}
var search_input = $('#input_search');
var search_console = search_input.val();
var header_console = $('.header');
$('#enter_console').click(function() {
var bodies = $('.reviews');
for(var i=0;i<bodies.length;i++){
var bodies = bodies[i];
if($(bodies).find(header_console).filter(':contains("+search_console+")')) {
bodies[i].hide();
}
}
});
I am trying to find if the bodies has the word that a user types in in the input. Then if that bodies has the word hide the rest of the elements except it. Can anyone help me??? Basic html looks like
<div id="2343" class="reviews">
<h2>Animal Crossing: City Folk</h2><h3 class="header">Wii</h3>
<p>8/10</p>
<img src="http://i1231.photobucket.com/albums/ee512/Rukiafan23/1_zpsdab192dc.jpg" alt="{title}">
<a href="http://www.wiiwarewave.com/t93-animal-crossing-city-folk">
Read this Review
</a>
<div class="inner_box_review">----</div>
</div>
This should do it:
$('#enter_console').click(function() {
var search_input = $('#input_search'),
search_console = search_input.val(),
header_console = $('.header');
$('.reviews:has(.header:contains("' + search_console + '"))').hide();
});
fixed a quote issue as well.
the selector says: "Select all elements with class "reviews" that have at least one descendant that contains the text stored within search_console."
If you need to do the opposite and hide all that DONT have said text, you need .not( or :not()
$('#enter_console').click(function() {
var search_input = $('#input_search'),
search_console = search_input.val(),
header_console = $('.header');
$('.reviews').not(':has(.header:contains("' + search_console + '"))').hide();
});
or
$('#enter_console').click(function() {
var search_input = $('#input_search'),
search_console = search_input.val(),
header_console = $('.header');
$('.reviews:not(:has(.header:contains("' + search_console + '")))').hide();
});
I have following html:
<div id="note">
<textarea id="textid" class="textclass">Text</textarea>
</div>
How can I get textarea element? I can't use document.getElementById("textid") for it
I'm doing it like this now:
var note = document.getElementById("note");
var notetext = note.querySelector('#textid');
but it doesn't work in IE(8)
How else I can do it? jQuery is ok
Thanks
If jQuery is okay, you can use find(). It's basically equivalent to the way you are doing it right now.
$('#note').find('#textid');
You can also use jQuery selectors to basically achieve the same thing:
$('#note #textid');
Using these methods to get something that already has an ID is kind of strange, but I'm supplying these assuming it's not really how you plan on using it.
On a side note, you should know ID's should be unique in your webpage. If you plan on having multiple elements with the same "ID" consider using a specific class name.
Update 2020.03.10
It's a breeze to use native JS for this:
document.querySelector('#note #textid');
If you want to first find #note then #textid you have to check the first querySelector result. If it fails to match, chaining is no longer possible :(
var parent = document.querySelector('#note');
var child = parent ? parent.querySelector('#textid') : null;
Here is a pure JavaScript solution (without jQuery)
var _Utils = function ()
{
this.findChildById = function (element, childID, isSearchInnerDescendant) // isSearchInnerDescendant <= true for search in inner childern
{
var retElement = null;
var lstChildren = isSearchInnerDescendant ? Utils.getAllDescendant(element) : element.childNodes;
for (var i = 0; i < lstChildren.length; i++)
{
if (lstChildren[i].id == childID)
{
retElement = lstChildren[i];
break;
}
}
return retElement;
}
this.getAllDescendant = function (element, lstChildrenNodes)
{
lstChildrenNodes = lstChildrenNodes ? lstChildrenNodes : [];
var lstChildren = element.childNodes;
for (var i = 0; i < lstChildren.length; i++)
{
if (lstChildren[i].nodeType == 1) // 1 is 'ELEMENT_NODE'
{
lstChildrenNodes.push(lstChildren[i]);
lstChildrenNodes = Utils.getAllDescendant(lstChildren[i], lstChildrenNodes);
}
}
return lstChildrenNodes;
}
}
var Utils = new _Utils;
Example of use:
var myDiv = document.createElement("div");
myDiv.innerHTML = "<table id='tableToolbar'>" +
"<tr>" +
"<td>" +
"<div id='divIdToSearch'>" +
"</div>" +
"</td>" +
"</tr>" +
"</table>";
var divToSearch = Utils.findChildById(myDiv, "divIdToSearch", true);
(Dwell in atom)
<div id="note">
<textarea id="textid" class="textclass">Text</textarea>
</div>
<script type="text/javascript">
var note = document.getElementById('textid').value;
alert(note);
</script>
Using jQuery
$('#note textarea');
or just
$('#textid');
$(selectedDOM).find();
function looking for all dom objects inside the selected DOM.
i.e.
<div id="mainDiv">
<p>Paragraph 1</p>
<p>Paragraph 2</p>
<div id="innerDiv">
link
<p>Paragraph 3</p>
</div>
</div>
here if you write;
$("#mainDiv").find("p");
you will get tree p elements together. On the other side,
$("#mainDiv").children("p");
Function searching in the just children DOMs of the selected DOM object. So, by this code you will get just paragraph 1 and paragraph 2. It is so beneficial to prevent browser doing unnecessary progress.