I am using ckeditor inline on a webpage that i have built.I can save the data to a database but the major problem is that ckeditor applies its own classes and other attributes to all the elements on which contenteditable is set to true.Also it removes some classes on elements. This is affecting the styling of my webpage. I wish to remove the classes and other attributes set by ckeditor before printing it on the browser.For this I need to loop through all the elements having content editable set to true. How can we do this using js?
Plain JS:
var el = document.getElementsByTagName("*");
for(var i = 0, l = el.length; i < l; i++)
{
if (el[i].contentEditable)
{
// Do here what you want
}
}
jQuery:
as dandavis said:
$("*[contentEditable]").each(function()
{
//
});
Edit:
As far as the .contentEditable does not return boolean,
you must check whether the element has the contentEditable attribute like this:
var el = document.getElementsByTagName("*");
for(var i = 0, l = el.length; i < l; i++)
{
if (el[i].contentEditable === "true" || el[i].contentEditable === "")
{
// Do here what you want
}
}
In order to remove the contentEditable attribute:
In jQuery you can do it like this:
$("*[contentEditable]").each(function()
{
this.prop("contentEditable", false);
});
Plain js:
el[i].contentEditable = "false";
Related
How can this jQuery-dependent code
$('.myElement').click(function () {
drawMode = !drawMode;
$icon = $(this).children('i');
if (drawMode) {
$icon.removeClass('a').addClass('b');
} else {
$icon.removeClass('b').addClass('a');
}
});
be rewritten into native javascript?
I have tried
var element = document.getElementsByClassName('myElement')[0];
element.addEventListener('click', function (e) {
drawMode = !drawMode;
var icon = this.children()[0];
if (drawMode) {
icon.classList.remove('a').add('b');
} else {
icon.classList.remove('b').add('a');
}
});
but I cannot find the children element correctly.
jQuery's children allows you to filter by selector, something that isn't in the DOM API (you can find all descendants matching a given CSS selector, but you can't [for now] limit it to just children).
If it doesn't matter whether it's a child or just any descendant, then:
var icon = this.querySelector("i");
That finds the first descendant within the element that's an i element. I suspect that would work just fine for you. The only time it might not would be if you had this:
<div class="myElement">
<span>
<i>You DON'T want this one</i>
</span>
<i>You do want this one</i>
</div>
If that's the case and you need to only look at children, not all descendants, you'll need a loop:
var icon = null;
var n;
for (n = 0; n < !icon && this.children.length; ++n) {
if (this.children[n].tagName.toLowerCase() === "i") {
icon = this.children[n];
}
}
In ES2015+ (you can transpile to use it today), that's so much tidier:
let icon = Array.from(this.children)
.find(child => child.tagName.toLowerCase() === "i");
A few notes:
The add and remove functions of the classList do not return the classList object, so you can't concatenate them (e.add().remove(), like you are used to do in jQuery).
In your code you only go over the first element, while when using jQuery the changes are made for all elements that you selected.
I used the querySelectorAll and filtered out elements that are not direct childs, (checked for the parentElement since you used the children() function of jQuery).
Here is an example:
drawMode = true;
var elements = document.getElementsByClassName('myElement');
for (var i = 0; i < elements.length; i++) {
elements[i].addEventListener('click', function() {
var that = this;
drawMode = !drawMode;
var icons = this.querySelectorAll('i');
for (var j = 0; j < icons.length; j++) {
var icon = icons[j];
if (icon.parentElement != that) {
continue;
}
if (drawMode) {
icon.classList.remove('a');
icon.classList.add('b');
} else {
icon.classList.remove('b')
icon.classList.add('a');
}
}
});
}
i.a {
background: red;
}
i.b {
background: blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="myElement">
<i>asd</i><br />
<i>fgh</i><br />
<span><i>This element will not change because he isn't a direct child</i></span><br />
</div>
Generally, document.querySelectorAll is very useful when converting jQuery to vanilla javascript.
Returns a list of the elements within the document (using depth-first pre-order traversal of the document's nodes) that match the specified group of selectors. The object returned is a NodeList.
// get a NodeList of elements which match CSS Selector '.myElement'
var elements = document.querySelectorAll('.myElement');
for (var i = 0; i < elements.length; i++ ) {
// loop through every element with class 'myElement'
var element = elements[i];
element.addEventListener('click', function(event) {
drawMode = !drawMode;
var icon = element.querySelector('i');
if (drawMode) {
icon.classList.remove('a');
icon.classList.add('b');
} else {
icon.classList.remove('b');
icon.classList.add('a');
}
});
}
Note I've also used element.querySelector to match descendants of the currently processed element.
I have some div ids that are generated dynamicly via php
<div id='a<?php echo $gid?>>
How can I access them in JavaScript? All these divs start with "A" followed by a number.
Is there some kind of search function
getElementById(a*)?
Thanks for any help
No generic JavaScript function for this (at least not something cross browser), but you can use the .getElementsByTagName and iterate the result:
var arrDivs = document.getElementsByTagName("div");
for (var i = 0; i < arrDivs.length; i++) {
var oDiv = arrDivs[i];
if (oDiv.id && oDiv.id.substr(0, 1) == "a") {
//found a matching div!
}
}
This is the most low level you can get so you won't have to worry about old browsers, new browsers or future browsers.
To wrap this into a neater function, you can have:
function GetElementsStartingWith(tagName, subString) {
var elements = document.getElementsByTagName(tagName);
var result = [];
for (var i = 0; i < elements.length; i++) {
var element = elements[i];
if (element.id && element.id.substr(0, subString.length) == subString) {
result.push(element);
}
}
return result;
}
The usage example would be:
window.onload = function() {
var arrDivs = GetElementsStartingWith("div", "a");
for (var i = 0; i < arrDivs.length; i++) {
arrDivs[i].style.backgroundColor = "red";
}
};
Live test case.
In case you choose to use jQuery at some point (not worth for this thing alone) all the above code turns to single line:
$(document).ready(function() {
$('div[id^="a"]').css("background-color", "blue");
});
Updated fiddle, with jQuery.
No, you need a fixed id value for getElementById to work. However, there are other ways to search the DOM for elements (e.g. by CSS classes).
You can use querySelectorAll to get all divs that have an ID starting with a. Then check each one to see if it contains a number.
var aDivs = document.querySelectorAll('div[id^="a"]');
for(var index = 0, len = aDivs.length; index < len; index++){
var aDiv = aDivs[index];
if(aDiv.id.match(/a\d+/)){
// aDiv is a matching div
}
}
DEMO: http://jsfiddle.net/NTICompass/VaTMe/2/
Well, I question myself why you would need to select/get an element, that has a random ID. I would assume, you want to do something with every div that has a random ID (like arranging or resizing them).
In that case -> give your elements a class like "myGeneratedDivs" with the random ID (if you need it for something).
And then select all with javascript
var filteredResults=document.querySelectorAll(".myGeneratedDivs").filter(function(elem){
....
return true;
});
or use jQuery/Zepto/YourWeaponOfChoice
var filteredResults=$(".myGeneratedDivs").filter(function(index){
var elem=this;
....
return true;
});
If you plan to use jQuery, you can use following jQuery selectors
div[id^="a"]
or
$('div[id^="id"]').each(function(){
// your stuff here
});
You will have to target the parent div and when someone click on child div inside a parent div then you can catch the child div.
<div id="target">
<div id="tag1" >tag1</div>
<div id="tag1" >tag2</div>
<div id="tag1" >tag3</div>
</div>
$("#target").on("click", "div", function() {
var showid = $(this).attr('id');
alert(showid)
});
getElementById() will return the exact element specified. There are many javascript frameworks including jQuery that allow much more powerful selection capabilities. eg:
Select an element by id: $("#theId")
Select a group of elements by class: $(".class")
Select subelements: $("ul a.action")
For your specific problem you could easily construct the appropriate selector.
I have a button that is defined as follows :
<button type="button" id="ext-gen26" class=" x-btn-text">button text here</button>
And I'm trying to grab it based on the text value. Hhowever, none of its attributes contain the text value. It's generated in a pretty custom way by the look of it.
Does anyone know of a way to find this value programmatically, besides just going through the HTML text? Other than attributes?
Forgot one other thing, the id for this button changes regularly and using jQuery to grab it results in breaking the page for some reason. If you need any background on why I need this, let me know.
This is the JavaScript I am trying to grab it with:
var all = document.getElementsByTagName('*');
for (var i=0, max=all.length; i < max; i++)
{
var elem = all[i];
if(elem.getAttribute("id") == 'ext-gen26'){
if(elem.attributes != null){
for (var x = 0; x < elem.attributes.length; x++) {
var attrib = elem.attributes[x];
alert(attrib.name + " = " + attrib.value);
}
}
}
};
It only comes back with the three attributes that are defined in the code.
innerHTML, text, and textContent - all come back as null.
You can do that through the textContent/innerText properties (browser-dependant). Here's an example that will work no matter which property the browser uses:
var elem = document.getElementById('ext-gen26');
var txt = elem.textContent || elem.innerText;
alert(txt);
http://jsfiddle.net/ThiefMaster/EcMRT/
You could also do it using jQuery:
alert($('#ext-gen26').text());
If you're trying to locate the button entirely by its text content, I'd grab a list of all buttons and loop through them to find this one:
function findButtonbyTextContent(text) {
var buttons = document.querySelectorAll('button');
for (var i=0, l=buttons.length; i<l; i++) {
if (buttons[i].firstChild.nodeValue == text)
return buttons[i];
}
}
Of course, if the content of this button changes even a little your code will need to be updated.
One liner for finding a button based on it's text.
const findButtonByText = text =>
[...document.querySelectorAll('button')]
.find(btn => btn.textContent.includes(text))
A while ago I was making some test in JavaScript,
and played with a code to get the text of all elements with a certain class.
Now I was trying to make something like this but obtain all elements by a certain type, for example all elements type="text"
Is there any way to do this in JavaScript or should I use jQuery?
var xx = document.getElementsByClassName("class");
for (i=0;i<xx.length;i++){
var str=xx[i].innerHTML;
alert(str);
}
If you are lucky and need to care only for recent browsers, you can use:
document.querySelectorAll('input[type=text]')
"recent" means not IE6 and IE7
In plain-old JavaScript you can do this:
var inputs = document.getElementsByTagName('input');
for(var i = 0; i < inputs.length; i++) {
if(inputs[i].type.toLowerCase() == 'text') {
alert(inputs[i].value);
}
}
In jQuery, you would just do:
// select all inputs of type 'text' on the page
$("input:text")
// hide all text inputs which are descendants of div class="foo"
$("div.foo input:text").hide();
The sizzle selector engine (what powers JQuery) is perfectly geared up for this:
var elements = $('input[type=text]');
Or
var elements = $('input:text');
var inputs = document.querySelectorAll("input[type=text]") ||
(function() {
var ret=[], elems = document.getElementsByTagName('input'), i=0,l=elems.length;
for (;i<l;i++) {
if (elems[i].type.toLowerCase() === "text") {
ret.push(elems[i]);
}
}
return ret;
}());
I have a form that pop up inside a layer, and I need to make everything inside that form read only regarding what type of input it is. Anyway to do so?
This is quite simple in plain JavaScript and will work efficiently in all browsers that support read-only form inputs (which is pretty much all browsers released in the last decade):
var form = document.getElementById("your_form_id");
var elements = form.elements;
for (var i = 0, len = elements.length; i < len; ++i) {
elements[i].readOnly = true;
}
With HTML5 it's possible to disable all inputs contained using the <fieldset disabled /> attribute.
disabled:
If this Boolean attribute is set, the form controls that are its
descendants, except descendants of its first optional
element, are disabled, i.e., not editable. They won't received any
browsing events, like mouse clicks or focus-related ones. Often
browsers display such controls as gray.
Reference: MDC: fieldset
You can use the :input selector, and do this:
$("#myForm :input").prop('readonly', true);
:input selects all <input>, <select>, <textarea> and <button> elements. Also the attribute is readonly, if you use disabled to the elements they won't be posted to the server, so choose which property you want based on that.
Its Pure Javascript :
var fields = document.getElementById("YOURDIVID").getElementsByTagName('*');
for(var i = 0; i < fields.length; i++)
{
fields[i].disabled = true;
}
Old question, but nobody mentioned using css:
pointer-events: none;
Whole form becomes immune from click but also hovers.
You can do this the easiest way by using jQuery. It will do this for all input, select and textarea elements (even if there are more than one in numbers of these types).
$("input, select, option, textarea", "#formid").prop('disabled',true);
or you can do this as well but this will disable all elements (only those elements on which it can be applied).
$("*", "#formid").prop('disabled',true);
disabled property can applies to following elements:
button
fieldset
input
optgroup
option
select
textarea
But its upto you that what do you prefer to use.
Old question, but right now you can do it easily in pure javascript with an array method:
form = document.querySelector('form-selector');
Array.from(form.elements).forEach(formElement => formElement.disabled = true);
1) form.elements returns a collection with all the form controls (inputs, buttons, fieldsets, etc.) as an HTMLFormControlsCollection.
2) Array.from() turns the collection into an array object.
3) This allows us to use the array.forEach() method to iterate through all the items in the array...
4) ...and disable them with formElement.disabled = true.
$("#formid input, #formid select").attr('disabled',true);
or to make it read-only:
$("#formid input, #formid select").attr('readonly',true);
Here is another pure JavaScript example that I used. Works fine without Array.from() as a NodeList has it's own forEach method.
document.querySelectorAll('#formID input, #formID select, #formID button, #formID textarea').forEach(elem => elem.disabled = true);
// get the reference to your form
// you may need to modify the following block of code, if you are not using ASP.NET forms
var theForm = document.forms['aspnetForm'];
if (!theForm) {
theForm = document.aspnetForm;
}
// this code disables all form elements
var elements = theForm.elements;
for (var i = 0, len = elements.length; i < len; ++i) {
elements[i].disabled = true;
}
This one has never failed me and I did not see this approach on the other answers.
//disable inputs
$.each($("#yourForm").find("input, button, textarea, select"), function(index, value) {
$(value).prop("disabled",true);
});
disable the form by setting an attribute on it that disables interaction generally
<style>form[busy]{pointer-events:none;}</style>
<form>....</form>
<script>
function submitting(event){
event.preventDefault();
const form = this; // or event.target;
// just in case...
if(form.hasAttribute('busy')) return;
// possibly do validation, etc... then disable if all good
form.setAttribute('busy','');
return fetch('/api/TODO', {/*TODO*/})
.then(result=>{ 'TODO show success' return result; })
.catch(error=>{ 'TODO show error info' return Promise.reject(error); })
.finally(()=>{
form.removeAttribute('busy');
})
;
}
Array.from(document.querySelectorAll('form')).forEach(form=>form.addEventListener('submit',submitting);
</script>
Javascript : Disable all form fields :
function disabledForm(){
var inputs = document.getElementsByTagName("input");
for (var i = 0; i < inputs.length; i++) {
inputs[i].disabled = true;
}
var selects = document.getElementsByTagName("select");
for (var i = 0; i < selects.length; i++) {
selects[i].disabled = true;
}
var textareas = document.getElementsByTagName("textarea");
for (var i = 0; i < textareas.length; i++) {
textareas[i].disabled = true;
}
var buttons = document.getElementsByTagName("button");
for (var i = 0; i < buttons.length; i++) {
buttons[i].disabled = true;
}
}
To Enabled all fields of form see below code
function enableForm(){
var inputs = document.getElementsByTagName("input");
for (var i = 0; i < inputs.length; i++) {
inputs[i].disabled = false;
}
var selects = document.getElementsByTagName("select");
for (var i = 0; i < selects.length; i++) {
selects[i].disabled = false;
}
var textareas = document.getElementsByTagName("textarea");
for (var i = 0; i < textareas.length; i++) {
textareas[i].disabled = false;
}
var buttons = document.getElementsByTagName("button");
for (var i = 0; i < buttons.length; i++) {
buttons[i].disabled = false;
}
}
As the answer by Tim Down I suggest:
const FORM_ELEMENTS = document.getElementById('idelementhere').elements;
for (i = 0; i < FORM_ELEMENTS.length; i++) {
FORM_ELEMENTS[i].disabled = true;
}
This will disable all elements inside a form.
for what it is worth, knowing that this post is VERY old... This is NOT a read-only approach, but works for me. I use form.hidden = true.
Thanks Tim,
That was really helpful.
I have done a little tweaking when we have controls and we handle a event on them.
var form = document.getElementById("form");
var elements = form.elements;
for (var i = 0, len = elements.length; i < len; ++i) {
elements[i].setAttribute("onmousedown", "");
}