I'm trying to make a simple image browser for TinyMCE which I am using in my CMS. As part of this I need to detect whether the user has selected an existing image, so I can display the "edit" form instead of the "choose an image form".
var selected_html = ed.selection.getContent();
var $elem = $(selected_html);
console.log($elem);
The first function returns the user selected text from the editor window as a string of HTML. I then would like to use jQuery (although plain javascript is just ok too) to check if this string contains an img tag before subsequently grabbing the src and title attributes for editing.
Now I've got as far as getting the html to turn into an object. But after this I can't manage to search it for the img element. After reading this (How to manipulate HTML within a jQuery variable?) I tried:
$elem.find('img');
But it just comes out as an "undefined" object...
I think I'm missing something fairly obvious here (it is getting late), but after an hour I still can't figure out how to grab the img tag from the selection. :(
Many thanks in advance.
Because the <img> is at the root of the jQuery object, you need to use .filter() instead of .find().
$elem.filter('img');
The .filter() method looks at the element(s) at the top level of the jQuery object, while .find() looks for elements nested in any of the top level elements.
If you're not sure beforehand where the target element will be, you could place the HTML into a wrapper <div> to search from. That way the HTML given will never be at the top.
var selected_html = ed.selection.getContent();
var $elem = $('<div>').html(selected_html);
var $img = $elem.find('img');
Try to see what is really inside your $elem variable. Just do a console.log($elem) using both Firefox and Firebug and you should be able to manage quite alright! ;)
Related
I have already found some question of this genre but the answer didn't help.
Javascript - div content without innerHTML
Javascript: Does not change the div innerHTML
I have a div called adx-title by id and i have to change the content. So i made my ajax call and i stored (i use jQuery) in a call the title i want this div to contain:
$('#adx-title').inneHTML = title;
Firebug report this ($('#adx-title').inneHTML) as undefined, and it does report so in every attempt i make to change the content of the div, which is read as an object but it doesn't have the innerHTML property. The script is loaded after i click a button so it should recognize the div as already loaded by the page. And indeed it gets the div with $('#adx-title'). it just doesn't apply the change and reports innerHTML as undefined.
Anyone has had a similar issue? Anyone can help? Thanks Agnese
You're using jQuery.
$('#adx-title').html( title );
The .innerHTML property is part of the DOM API. When you make a call to jQuery (as you're doing with the $) the result is a jQuery object, not a DOM element.
You can get the DOM element from the jQuery object like this:
var elem = $('#adx-title').get(0);
However, the jQuery .html() API wraps access to the .innerHTML property and also provides some other useful bookkeeping features. If you're using jQuery in general to manipulate the DOM, it's a good idea to use .html() and not the raw DOM API for that reason.
Try $('#adx-title').html(title);
I haven't dealt with javascript in a long time, so please bear with me if my question seems silly.
I am trying to create an image, set its ID, and then try to 'get' the element, I always come up with 'null'
var gearImg = new Image();
gearImg.id = "logoGear";
gearImg.src = "img/gear-fun.png";
var gear = document.getElementById("logoGear");
// null?
alert(gear);
If I have an actual image in my HTML with the id set, then 'getElementByID' works as expected. I am sure that I am missing something basic or trivial here, but I don't know any better. What is going on, and how do I get the behaviour that I want.
document.getElementById only deals with elements in your document. Since gearImg is not a part of the document, it returns nothing. Try putting it somewhere first, for example:
document.body.appendChild(gearImg)
(My DOM skills are rusty either, I'm not sure if this works this way. Why don't we simply use jQuery?)
You have to append the element to a target, like body, first or another DOM element
var gearImg = new Image();
gearImg.id = "logoGear";
gearImg.src = "img/gear-fun.png";
document.body.appendChild(gearImg); // add to body tag
var gear = document.getElementById("logoGear");
alert(gear);
To retrieve an element from the DOM you have to append it to the DOM first.
Use:
document.body.appendChild(gearImg);
Or:
someElement.appendChild(gearImg);
Then you can call document.getElementById('logoGear');
This is because you did not append the image to your document.
So when you do document.getElement.... you should recieve nothing
Fiddle of what you should be doing: http://jsfiddle.net/maniator/UPaUa/
Code:
var gearImg = new Image();
gearImg.id = "logoGear";
gearImg.src = "img/gear-fun.png";
document.body.appendChild(gearImg);
var gear = document.getElementById("logoGear");
alert(gear);
Element is not yet added to the DOM and therefore is not inside the document.
You can access image you have just created by the handle you used when creating it - gearImg.
Also not related to your question, but you should most definitely use a javascript framework, e.g. jQuery.
The because you didn't add gearing on your document..
that document.getElementById("") only work with document elements... like tables, rows that already exist on the document page.
This is because document.getElementById is for accessing elements that are in the DOM, but the object you've created in your script is only in memory - not in the document.
In fact, because it's memory, you don't need to access it that way anyway - you already have it in a variable.
What are you actually trying to achieve? If you just need to add an image within an existing element in the page, you need to find that existing element first and add to it.
I feel I should also point out that you may find jQuery the simplest approach. It makes it very easy indeed to play around with the content of a page.
javascript:var t=document.querySelector('[id^="profile_pic_header_"').id.split('_');document.write(JSON.stringify({FacebookId:t[t.length-1], Token:window.location.hash.split('&')[0].split('access_token=')[1]}));
I am currently trying to figure out a way to work within a selected <div> in order to be able to send a text formatted email.
So there is a button says "email". When a user clicks on it, it grabs a closest div as below.
var selectedDiv = $(callingElement).closest(".myClassName");
And from there I would like to grab various dom elements to create a clean text format. So how do I work within selectedDiv using jQuery?
For example,
Getting <h1> value.
Getting <li> value with certain class names
Getting "title" attribute value.
The selectedDiv jQuery object wraps the div element. Use the find method to search for descendant elements, and attr to get the attributes on the div element itself.
selectedDiv.find('h1');
selectedDiv.find('li.someClass');
selectedDiv.attr('title');
Call the text() method to get the text from the h1, or the li.
selectedDiv.find('h1').text();
selectedDiv.children('h1').text();
selectedDiv.children('li.className').text();
selectedDiv.attr('title');
But somehow I think you might be asking the "wrong" question.
I'm wondering what might be the simplest approach to dynamically changing the contents of a "caption" div to reflect the info corresponding to a specific thumbnail/link in an image gallery.
To be more specific, if you visit this link-- which shows off the awesome Seadragon zoom script btw-- I would like to have a small caption under the image that changes (text) content when a user clicks the different links above; perhaps pulling text from an alt or title attribute and placing in an empty div?
In my case, I'll be using thumbnails instead of text links, so upon clicking these images the user will both initiate the "switchTo" Seadragon event and fill the empty div with corresponding content.
thanks for any guidance here.
If you have the id of the div, the simplest way would be to use innerHTML:
document.getElementById(id).innerHTML = "text";
This is fine for simpler cases, like replacing all of the text in a div. If you want to do something more complicated, like having other html elements inside the div, this method is not the best choice.
If you want to add an html element to the div tag, then you should avoid innerHTML. If you have, say, a variable img that is an img tag, then use this to add it to the div:
document.getElementById(id).appendChild(img);
If you want to do anything more complicated than this, you should probably consider using a nice framework like jQuery--it might be too much for something like this, but if you plan to do anything else, then a framework would be worth using.
If you want to do this with jQuery, it can be done using some of the following functions:
var div = $("#id");// jQuery uses CSS selectors to get elements.
div.append("New content");// Puts the new content at the end.
div.empty();// Gets rid of everything inside the div.
div.append(element);// You can also append elements.
// For example, you can create and append an image to the div:
var img = $("<img>");
img.attr("src", "images/something.png");
div.append(img);
I want to know the most effctive way to dynamically update, insert or remove elements from an html page.
The outcome of this is that, I can change an input element into a div element and vice versa based on a user action.
eg
<form><input type="text" value="Value to save"/></form>
and based on some event, i will change that to
<form><div>Value to Save</div></form>
Tx
I think you could do this task this way (pure JS, without using external frameworks):
//retrieve the <form>
var form = document.getElementsByTagName('form')[0];
//retrieve the <input> inside the form
var input = form.getElementsByTagName('input')[0];
//create a new <div> DOM element
var newElement = document.createElement('div');
//The containing div text is equal to the input value (your case)
newElement.innerHTML = input.value;
//simple empty the form by set innerHTML = ""
form.innerHTML = "";
//append the <div> inside the form
form.appendChild(newElement);
By the way, I sugges you, if you want to manipulate DOM and do stuff like these in an easier way, learn how to do it by using frameworks like jQuery or mootools ;)
This is a general description:
Creating: You can create elements with document.createElement and then use one the various insertion methods to the insert the element at a certain position (e.g. Node.appendChild). You need to get references to related nodes first.
Most browser also support the innerHTML attribute for elements. You can set that attribute to an HTML(or text) string and the content of the element will be updated accordingly.
Updating: It depends on which data you want to update. E.g. an input element has an attribute value. In order to change the value of a text input you need to get a reference to that element first, then you can do element.value = 'new value'. For content, you can use the already mentioned innerHTML attribute.
Have a look at an HTML element reference to see what attributes they have.
Deleting: You want Node.removeChild.
I suggest to also have a look at DOM traversal methods and be aware of browser differences.
Using:
element.removeChild
element.appendChild
By using these methods, you can retain references to the elements in case you want to swap them back over again. Any event handlers in place will remain attached to the elements, too.
This depends on your definition of most effective.
If you mean the simplest way, then you can use a library like jQuery and do it like this:
$('form').html('<dynamic markup>');
If you mean the most performant way you can do the following:
document.getElementByTagName('form').innerHTML = '<dynamic markup>';