How can change div textContent without use getElementsByName or getElementsById? - javascript

How can change div textContent without use getElementsByName or getElementsById?
I have a code like this :
function get_up_vote_text() {
var up_text=document.createElement('div');
up_text.setAttribute('name','up_text');
up_text.textContent='152';
return up_text;
}
And I want update "up_text" value in the following function (without using getElementsByName or getElementsById) :
function get_up_vote() {
var up = document.createElement('div');
up.setAttribute('name','up');
up.onclick=function () {
var temp=get_up_vote_text();
//I want write some code here to update "up_text" value
}
return up;
}

You could use this object :
up.onclick=function () {
var temp=get_up_vote_text();
this.textContent="new text content";
}
OR also from event using e.target :
up.onclick=function (e) {
var temp=get_up_vote_text();
e.target.textContent="new text content";
}
Hope this helps.

you can use jquery for it, use these tags on your HTML page
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
</head>
then if your div has a id = divID simply use $("#divID") to get the div you want

Related

Append text into div element when click using jquery

Using the below code I append some input elements into the #cls div. But when I try to type inside the input also new input add. I only need new input when I click "click" text. Can anyone help me. Thank you
$('#cls').click(function() {
var add="<input type="text">"
$(#cls).append(add);
});
<div id="cls">click</div>
You need to see whether the click actually happened in the div
$('#cls').click(function(e) {
if ($(e.target).is(this)) { //or !$(e.target).is('input')
var add = '<input type="text">';
$(this).append(add);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="cls">click</div>
If you user .after() method instead of .append() the textbox would appear outside the #cls div and hence clicking the textbox wouldn't cause adding a new one.
Some code
$('#cls').click(function() {
var add="<input type='text'>";
$('#cls').after(add);
});
Try it out
Append your input to parent element:
var clicked= false;
$('#cls').click(function() {
if(!clicked){
var add="<input type='text'>";
$(this).parent().append(add);
clicked = true;
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='cls'>click</div>
use jQuery's one method. it will register click handler only once.
$('#cls').one("click", function(e) {
var add = '<input type="text">';
$(this).append(add);
});

appendChild is not a function - what am I doing wrong?

I know this is a very common error, but I just can't figure out why this isn't working.
I want to change the value of a span dynamically. Simple, right? I've tried $span.innerHTML = "text" and $span.innerText = "text", which do nothing, but don't throw any errors. My most recent attempt looks like this:
var $resourceSpan = $("#divname"+dynamic_variable);
var stringVar = functionThatReturnsString();
while( $resourceSpan.firstChild ) {
$resourceSpan.removeChild( $resourceSpan.firstChild );
}
var textNode = document.createTextNode(stringVar);
$resourceSpan.appendChild( textNode );
Does anyone know why I'm throwing this error? Thanks
You are dealing with jQuery object, methods like removeChild() and appendChild() belongs to dom element not to the jQuery object.
To remove all contents of an element you can use .empty() and to set the text content of an element you can use .text(), but using .text() will replace existing content so in your case you can just use
var $resourceSpan = $("#divname" + dynamic_variable);
var stringVar = functionThatReturnsString();
$resourceSpan.text(stringVar);
Did you wanna do somethin like this?
<html>
<head>
<title>STACK OVERFLOW TESTS</title>
<style>
</style>
</head>
<body>
<span>HI, IM SOME TEXT</span>
<input type = 'button' value = 'Click me!' onClick = 'changeText()'></input> <!-- Change the text with a button for example... -->
<script>
var text = 'I AM THE NEW TEXT'; // The text to go in the span element
function changeText(){
var span = document.querySelector('span');
span.innerHTML = text;
}
</script>
</body>
</html>

How to reference an id with brackets in jQuery

I'm painfully new to jQuery and I need to grab the value on change of a text input box with an id of id[2][t] and display that text in a div to be styled later on (also styled with jQuery).
This is the input box code:
<input id="id[2][t]" name="id[2][t]" maxlength="20" type="text">
This is the div I am trying to display it in:
<div id="textpreview"></div>
This is what I have tried, among other variation with no success:
$(document).ready(function() {
$('#id\\[2\\]\\[t\\]').change(function() {
var txtval = $('#id\\[2\\]\\[t\\]').text();
$("#textpreview").val(txtval);
});
});
I know the brackets are a problem but they need to remain for other reasons.
Any ideas?
$( document.getElementById( "id[2][t]" ) ).change( function(){
$( "#textpreview" ).text( this.value );
} );
You might consider revising your IDs (though I'm guessing they might be auto-generated). According to this question your IDs are invalid against the spec
Use the attribute selector instead:
var sel = $("[id='id[2][t]']");
sel.change(function() {
$("#textpreview").val(sel.text());
});
Plain Old JavaScript:
var elem = document.getElementById('id[2][t]');
elem.onchange = function()
{
var elem = document.getElementById('textpreview');
elem.removeChild(elem.firstChild)
elem.appendChild(document.createTextNode(this.value));
}
Ahhh... now doesn't that feel better?
You have val and text backwards. Swap them:
$('#id\\[2\\]\\[t\\]').change(function() {
var txtval = $('#id\\[2\\]\\[t\\]').val();
$("#textpreview").text(txtval);
});
val is used to get the value of the textbox. text to set the text within the div.
You can further simplify the code by using this instead of re-querying the element.
$('#id\\[2\\]\\[t\\]').change(function() {
var txtval = this.value;
$("#textpreview").text(txtval);
});
You can try using the attribute selector instead of the id selector.
$('[id="id[2][t]"]')

Replace text with HTML element

How can I replace a specific text with HTML objects?
example:
var text = "some text to replace here.... text text text";
var element = $('<img src="image">').event().something...
function ReplaceWithObject(textSource, textToReplace, objectToReplace);
So I want to get this:
"some text to replace < img src...etc >.... text text text"
And I would like manipulate the object element without call again $() method.
UPDATE:
I solved.
thanx #kasdega, i made a new script based in your script, because in your script i can't modify the "element" after replace.
This is the script:
$(document).ready(function() {
var text = "some text to replace here.... text text text";
var element = $('<img />');
text = text.split('here');
$('.result').append(text[0],element,text[1]);
$(element).attr('src','http://bit.ly/mtUXZZ');
$(element).width(100);
});
I didnt know that append method accept multiples elements.
That is the idea, only need to automate for multiple replacements
thanx to all, and here the jsfiddle
do a split on the text you want to replace then use the array indexes 0 and 1...something like:
function ReplaceWithObject(textSource, textToReplace, objectToReplace) {
var strings = textSource.split(textToReplace);
if(strings.length >= 2) {
return strings[0] + objectToReplace.outerHTML() + strings[1];
}
return "";
}
UPDATE: I found another SO post Get selected element's outer HTML that pointed me to a tiny jquery plugin that helps here.
I believe this jsfiddle has what you want. outerHTML is the tiny jquery plugin I included in the JSFiddle.
You can also use replace which will reduce some code: http://jsfiddle.net/kasdega/MxRma/1/
function ReplaceWithObject(textSource, textToReplace, objectToReplace) {
return textSource.replace(textToReplace, objectToReplace.outerHTML());
}
function textToObj (text,obj,$src){
var className = "placeholder-"+text;
$src.html($src.html().replace(text,"<div class='"+className+"'></div>"));
$("."+className).replace(obj);
}
you can use $(selector).outerHtml to get the html string of an element
You can replace the html directly: http://jsfiddle.net/rkw79/qNFKF/
$(selector).html(function(i,o) {
return o.replace('old_html','new_html');
})

What is wrong with my Javascript?

This is my jsfiddle(http://jsfiddle.net/mZGsp/). I was trying to answer a question here but my code won't work. Here is the code:
JS
var stateOfClick = null;
function initiateLine(){
document.getElementById('test').innerHtml = "Started";
}
function endLine(){
document.getElementById('test').innerHtml = "Line Ended";
}
function createLines(){
if(!stateOfClick) {
initiateLine();
stateOfClick = 1;
} else {
endLine();
}
}
HTML
<body>
<input type="text" id="test" onclick="createlines()">
</body>
A couple of things,
change createlines() to createLines (camel-case).
change <element>.innerHtml to <element>.value
Inside JSFiddle, don't wrap your code inside a function, as then createLines won't be global which it needs to be for the onclick to work.
Here's a working example.
Not even this simple example will work on jsFiddle. You need to attach the event listener with JavaScript:
document.getElementById("someElement").onclick = function() {
//Do stuff
}
For input element you must use the value attribute not the innerHTML field.
function initiateLine(){
document.getElementById('test').value = "Started";
}
also you've misspelled the innerHTML function (though not the primary problem). innerHTML is used for html elements that can contain other elements such as a div containg a p element. Input and option elements all have a value attribute that can be used to extract or set their values.

Categories

Resources