Jquery append element and then alter css? - javascript

I'm attempting to create a div tag and then alter it via css, but for some reason its not working here's my code:
$('#draw').click(function(e){
var divToAdd = "<div id='box' style='display:block;background-color:red;width:100px;height:100px'></div>";
$("#area").append(divToAdd);
});
$('#left').click(function(e){
//var leftNow = document.getElementById("box").left + 1;
alert(document.getElementById("box").left);
$("#box").css('left',leftNow);
});
$('#right').click(function(e){
var leftNow = document.getElementById("box").left - 1;
$("#box").css("left","90");
});
So for some reason the value of document.getElementById("box").left is undefined. I've been trying to figure this out for a while, i've probably got something wrong in my syntax perhaps? Any help would be appreciated, thanks alot! Thank you Nick Craver.

You would need .style.left, or $("#box").css('left'); in this case.
But...there's an easier way, like this:
$("#box").css("left","-=1");
You can just make it relative this way, same for +=, keep it simple :)

Here I have two suggestions:
(1)Use jQuery object instead of object itself
var divToAdd = $("<div id='box' style='display:block;background-color:red;width:100px;height:100px'></div>");
Actually the expression above is not so good either, to make it more 'jQuery":
var divToAdd = $('<div></div>').css('background-color','red').css....
(2) Keep using jQuery if you involved it
$('#box').css('left') instead of document.getElemengById(...)

Related

How to fill this textbox? [duplicate]

I need to set the text within a DIV element dynamically. What is the best, browser safe approach? I have prototypejs and scriptaculous available.
<div id="panel">
<div id="field_name">TEXT GOES HERE</div>
</div>
Here's what the function will look like:
function showPanel(fieldName) {
var fieldNameElement = document.getElementById('field_name');
//Make replacement here
}
You can simply use:
fieldNameElement.innerHTML = "My new text!";
Updated for everyone reading this in 2013 and later:
This answer has a lot of SEO, but all the answers are severely out of date and depend on libraries to do things that all current browsers do out of the box.
To replace text inside a div element, use Node.textContent, which is provided in all current browsers.
fieldNameElement.textContent = "New text";
function showPanel(fieldName) {
var fieldNameElement = document.getElementById("field_name");
while(fieldNameElement.childNodes.length >= 1) {
fieldNameElement.removeChild(fieldNameElement.firstChild);
}
fieldNameElement.appendChild(fieldNameElement.ownerDocument.createTextNode(fieldName));
}
The advantages of doing it this way:
It only uses the DOM, so the technique is portable to other languages, and doesn't rely on the non-standard innerHTML
fieldName might contain HTML, which could be an attempted XSS attack. If we know it's just text, we should be creating a text node, instead of having the browser parse it for HTML
If I were going to use a javascript library, I'd use jQuery, and do this:
$("div#field_name").text(fieldName);
Note that #AnthonyWJones' comment is correct: "field_name" isn't a particularly descriptive id or variable name.
I would use Prototype's update method which supports plain text, an HTML snippet or any JavaScript object that defines a toString method.
$("field_name").update("New text");
Element.update documentation
$('field_name').innerHTML = 'Your text.';
One of the nifty features of Prototype is that $('field_name') does the same thing as document.getElementById('field_name'). Use it! :-)
John Topley's answer using Prototype's update function is another good solution.
The quick answer is to use innerHTML (or prototype's update method which pretty much the same thing). The problem with innerHTML is you need to escape the content being assigned. Depending on your targets you will need to do that with other code OR
in IE:-
document.getElementById("field_name").innerText = newText;
in FF:-
document.getElementById("field_name").textContent = newText;
(Actually of FF have the following present in by code)
HTMLElement.prototype.__defineGetter__("innerText", function () { return this.textContent; })
HTMLElement.prototype.__defineSetter__("innerText", function (inputText) { this.textContent = inputText; })
Now I can just use innerText if you need widest possible browser support then this is not a complete solution but neither is using innerHTML in the raw.
If you really want us to just continue where you left off, you could do:
if (fieldNameElement)
fieldNameElement.innerHTML = 'some HTML';
nodeValue is also a standard DOM property you can use:
function showPanel(fieldName) {
var fieldNameElement = document.getElementById(field_name);
if(fieldNameElement.firstChild)
fieldNameElement.firstChild.nodeValue = "New Text";
}
el.innerHTML='';
el.appendChild(document.createTextNode("yo"));
If you're inclined to start using a lot of JavaScript on your site, jQuery makes playing with the DOM extremely simple.
http://docs.jquery.com/Manipulation
Makes it as simple as:
$("#field-name").text("Some new text.");
Use innerText if you can't assume structure
- Use Text#data to update existing text
Performance Test
function showPanel(fieldName) {
var fieldNameElement = document.getElementById(field_name);
fieldNameElement.removeChild(fieldNameElement.firstChild);
var newText = document.createTextNode("New Text");
fieldNameElement.appendChild(newText);
}
Here's an easy jQuery way:
var el = $('#yourid .yourclass');
el.html(el.html().replace(/Old Text/ig, "New Text"));
In HTML put this
<div id="field_name">TEXT GOES HERE</div>
In Javascript put this
var fieldNameElement = document.getElementById('field_name');
if (fieldNameElement)
{fieldNameElement.innerHTML = 'some HTML';}

Saving data-attributes in Jquery

I would like to loop through a page of and store every with the data attribute of "agencyname". Although, my JQuery code doesnt allow me to do so. Can someone take a look and let me know what I am doing wrong, thanks.
The HTML
First
The Jquery:
var myVals = [];
$('a').data('agencyname').map(function(){
myVals.push($(this).attr('value'));
});
Try this using attribute selectors.
var myVals = $('a[data-agencyname]').map(function(){
return $(this).data('agencyname');
}).get();
DEMO

issues replacing html with link JavaScript

I'm trying to make a text into a link in my Javascript code. This should work but it doesn't.
var strLink = "mysite.com" ;
var cb_header = chatbox.find('.imjs-header');
cb_header.html(cb_header.html().replace('{username}', strLink));
I have a variable called username and it is a string. That is the string that used to replace {username}. Maybe I can use jquery? I can't seem to get it a link though. Any pointers in the right direction are greatly appreciated.
Thank you,
Arjun
var strLink = '"mysite.com" ';
Try this:
var strLink = '"mysite.com" ';

Remove special character (ampersand) from a string with jQuery or javascript

I'm trying to achieve something that 'should' be fairly straightforward, bit I can't find anything online to help me out.
I have some CSS class names that are being output with ampersands in them (its down to the system I'm using and is unavoidable). I'd like to use a little bit of jQuery to simply remove the ampersand, so a string that looks like:
class="Middle&East"
would be
class="MiddleEast"
Any help with this would be very much appreciated.
Thanks
To replace them all you could;
$('[class*=\\&]').each(function() {
$(this)[0].className = $(this)[0].className.replace(/&/g,"");
})
​
Try:
var class="Middle&East"
class.replace('&', '');
You will have to escape the & if you are using jquery
Try
$(".Middle\\&East").removeClass("Middle&East").addClass("MiddleEast");
DEMO
General solution to remove & from classname
$(function(){
$('[class*="&"]').each(function(){
var $this = $(this),cname = $this.attr('class').replace(/&/g,'');
$this.attr('class',cname)
})
})
Maybe something along
$(".Middle&East").removeClass("Middle&East").addClass("MiddleEast");
This one seems to works for me :
$(function() {
$('[class="Middle&East"]').toggleClass('Middle&East MiddleEast');
});
Here's a jsfiddle : http://jsfiddle.net/U3r7G/
var className = $(element).attr('class');
var modifiedClass = className.replace('&', '');
$(element).attr('class', modifiedClass);

jQuery how to insert <br/> tag after every Semicolon

I am dumping some CSS into a div and I am looking to format it so it is more legible. Basically what I want to do is insert a break tag after every semicolon. I have searched around for a while but can't seem to find something that quite fits what I am trying to do.
I have something like this...
HTML
<div class='test'>
color:red;background-color:black;
</div>​
jQuery
var test = $('.test').text();
var result = test.match(/;/g);
alert(result);​
And I have tried..
var test = $('.test').text();
var result = test.match(/;/g);
result.each(function(){
$('<br/>').insertAfter(';');
});
alert(result);​
Also I have started a fiddle here.. Which basically just returns the matched character...
http://jsfiddle.net/krishollenbeck/zW3mj/9/
That is the only part I have been able to get to work so far.
I feel like I am sort of heading down the right path with this but I know it isn't right because it errors out. I am thinking there is a way to insert a break tag after each matched element, but I am not really sure how to get there. Any help is much appreciated. Thanks...
try it like this
var test = $('.test').text();
var result = test.replace(/\;/g,';<br/>');
$('.test').html(result);​
http://jsfiddle.net/Sg5BB/
You can use a normal javascript .replace() method this way:
​$(document)​.ready(function(){
$(".test").html($(".test").html().replace(/;/g, ";<br />"));
});​
Fiddle: http://jsfiddle.net/SPBTp/4/
Use This CODE
var test = $('.test').text();
var result = test.split(';').join(';<br />')
http://jsfiddle.net/FmBpF/
You can't use jQuery selectors on text, it only works on elements.
Get the text, just replace each ; with ;<br/>, and put it back.
$('.test').html($('.test').text().replace(/;/g, ';<br/>'));
Try something like this :
var test = $('.test').text();
var result = test.replace(/;/g,";");
$('.test').html(result);
​
That should work if you stick it into your jfiddle.

Categories