dom – Javascript, porque somente document tem o metodo getElementById()?

A pegunta é simples, porque o javascript só permite fazer chamadas ao método getElementById() na raiz da árvore DOM? Em outras palavras? porque somente o objetvo document tem o método getElementById().

A razão da minha pergunta é a impossibilidade de pesquisar por um elemento de id unico a partir de um elemento qualquer.

A situação fica ainda mais curiosa quando se descobre o método querySelector() que pode ser chamado em qualquer elemento da arvore DOM, mas com uma limitação enorme: ELA NÃO PERMITE ALTERAÇÃO DOS ELEMENTOS.

então gostaria que pudessem me indicar bons materiais pra entender esse fenômeno tão contraditório.

plugin development – HTMLCollection not counting right in editor? / for loop not working on elements in DOM

I’m migrating my front-end code for a plugin to React and ESNext, and am still new to all of this, but for some reason, this really simple for loop isn’t executing on the admin edit page, but is fine when viewing the post. The only thing I can see is that there seems to be a weird issue with how HTMLCollections are counted, on the back end. I have this code:

/*
 * external dependencies
 */
import * as React from "react";
import { render } from "react-dom";

export default class App extends React.Component {
        render() {
                return (
                        <div className={"myapp-container"}>
                           // this is a test
                        </div>
                );
        }
}

document.addEventListener("DOMContentLoaded", (event) => {
        let els = document.getElementsByClassName("myapp_wrapper_class");
        console.log("got elements ", els); // this fires fine, everywhere

        for (let el of els) {
                console.log("working with ", el); // this fires on the front-end, but not in the editor
                render(<App />, document.getElementById(el.id));
        }
});

When I look at the console, on the front end, it logs

got elements 
HTMLCollection (1) // note this "1"
0 <div id="myApp1" style="width: 100%; height: 300px;" class="myapp myapp_wrapper_class" data-cwragc-src="https://localhost:8888/wp-content/uploads/2021/01/nakaza.csv" data-cwragc-type="line"></div>

but in the editor, it logs

got elements 
HTMLCollection (0) // note this "0"
0 <div id="myApp1" style="width: 100%; height: 300px;" class="myapp myapp_wrapper_class" data-cwragc-src="https://localhost:8888/wp-content/uploads/2021/01/nakaza.csv" data-cwragc-type="line"></div>

I’m unsure whether that zero is the problem, but like I said, it’s the only thing I can see that’s weird. There are no error messages in the console. I am sure that the for loop isn’t being executed on the back end, even though the element is there (as you can see in the console log), and exists in the rendered DOM.

The elements are created with a server-side render. In the block’s edit function, it looks thusly:

export function MyAppEdit( props ) {
//...
        const MyAppRender = () => {
                return(
                    <Disabled>
                        <ServerSideRender
                            block={ props.name }
                            attributes={{ ...attributes }} />
                    </Disabled>
                );
        }
//...
        return (
                <>
                        { controls }
                        <div { ...blockProps }>
                                { cwragcLocalFile && <MyAppRender /> }
                                { myAppPlaceholder }
                        </div>
                </>
        );
}
export default withNotices( MyAppEdit );

Grasping at straws, I also tried removing the <Disabled> wrapper on the editor side, but no change in effect.

Basically, I have no idea what’s going on here, but I’d like my stuff to render on the back end 🙂

Is it possibly a Babel bug? Is there some difference/timing/race issue with when DOMContentLoaded fires on the back end? Is there some better/more naturally React way for me to add a component to a div when I don’t know how many of them there will be (other than getElementsByClassName after DOMContentLoaded?

For completeness’ sake, my webpack is this:

const defaultConfig = require( '@wordpress/scripts/config/webpack.config' );
const path = require('path');

module.exports = {
    ...defaultConfig,
    entry: {
        myAppAdmin:
            path.resolve( process.cwd(), 'admin/src', 'index.js' ),
        myAppPublic:
            path.resolve( process.cwd(), 'public/src', 'index.js' ),
    },
    output: {
        filename: '(name).js',
        path: path.resolve( process.cwd(), 'assets/js' ),
    },
}

Maybe I’m missing some other require? But, like I said, it’s not generating any errors. admin/src/index.js is the block code; public/src/index.js is front-end code I’m trying to migrate, that adds React stuff after the server-side render.

não consigo criar uma imagem no DOM com javascript

Verificador de Idade

Verificador de idade

Ano de Nascimento:

sexo:
Homem
Mulher
Calcular Idade

preencha os dados a cima para ver o resultado

© Curso em video

var calc = document.querySelector(‘div#calcular’);
calc.addEventListener(‘click’, calcular);

function calcular(){

const data = new Date();
const ano = data.getFullYear();
const anoNascimento = document.querySelector('input#anoNascimento');
const resultado = document.querySelector('div#resultado');

if( anoNascimento.value.length == 0 || anoNascimento.value>ano){
    window.alert('Dados incorretos, tente novamente');
}else{
    const sex = document.getElementsByName('checkSex');
    const idade = ano - Number(anoNascimento.value);
    var genero = '';
    resultado.innerHTML = `Idade calculada: ${idade}`;
    var img = document.createElement('img');
    img.setAttribute('id', 'foto');
    
    if(sex(0).checked){
        genero='homem';
        if(idade>=0 && idade<10){
            img.setAttribute =('src', 'criancaMasculino.jpg');
        }else if(idade<20){
            img.setAttribute=('src','adolescenteMasculino.jpg');
        }else if(idade<50){
            img.setAttribute=('src', 'adulto.jpg');
        }else{
            img.setAttribute=('src', 'idoso.jpg');
        }
    }else if(sex(1)){
        genero='mulher';

        if(idade>=0 && idade<=10){
            img.setAttribute=('src', 'criancaFeminino.jpg');
        }else if(idade<20){
            img.setAttribute=('src', 'adolescenteFeminino.jpg');
        }else if(idade<50){
            img.setAttribute=('src', 'adulta.jpg');
        }else{
            img.setAttribute=('src', 'idosa.jpg');
        }
    }
    resultado.innerHTML=`Detectamos ${genero} com ${idade} anos.`;
    resultado.appendChild('img');
}

}

Scraping Question – PHP Simple HTML DOM

Now I opened this thread two days ago[URL="http://sonicsquirrel.net/det… | Read the rest of https://www.webhostingtalk.com/showthread.php?t=1834032&goto=newpost

Python With Beautiful Soup Or PHP With Simple HTML Dom

For scraping Amazon specific products, sorting them and comparing their prices. Which one is prefe… | Read the rest of https://www.webhostingtalk.com/showthread.php?t=1833709&goto=newpost

javascript – Como manipular o DOM de uma página antes dela terminar de carregar?

Estou fazendo um lazy loader em javascript puro, atualmente coloco meu script embed no fim do HTML que identifica as imagens e, caso elas não estejam prontas (por exemplo carregadas da cache), este muda a imagem para um placeholder mais leve e quando o usuário chega na imagem é carregada a imagem original.

Gostaria de saber se existe uma forma de eu achar as tags img enquanto o DOM é carregado, para conseguir substituir o src delas pelo meu placeholder antes mesmo de ser iniciada a solicitação pela imagem original (atualmente as solicitações que não estão em cache aparecem no inspetor como canceladas).

Caso queiram ver o código, ele está disponível no GitHub

Is this the proper way to write a javascript DOM function to create a bootstrap input group?

I got tasked with writing a page that will add as many profile entries as the user wants, and web programming is not at all my field. There are multiple input groups but I’m just using the “age” one as an example. Currently I’m using a function to create DOM elements, then I assemble them together and return the completed outer HTML code. Is this the correct way to do this? Here’s my code:

function addInputGroup(userID, userAge) {
                let ageCol = document.createElement('div');
                ageCol.setAttribute('class', 'col-4');
                
                let ageLabel = document.createElement('label');
                ageLabel.setAttribute('class', 'sr-only');
                ageLabel.innerHTML = "Age";
                
                let ageInputGroup = document.createElement('div');
                ageInputGroup.setAttribute('class', 'input-group');
                
                let ageInputGroupPrepend = document.createElement('div');
                ageInputGroupPrepend.setAttribute('class', 'input-group-prepend');
                
                let ageInputGroupText = document.createElement('div');
                ageInputGroupText.setAttribute('class', 'input-group-text');
                ageInputGroupText.innerHTML = "Age";
                
                let ageInput = document.createElement('input');
                ageInput.setAttribute('id', 'fldAge'+userID);
                ageInput.setAttribute('type', 'text');
                ageInput.setAttribute('class', 'form-control');
                ageInput.setAttribute('placeholder', userAge);
                ageInput.setAttribute('value', userAge);
                
                //assemble age column
                ageInputGroupPrepend.appendChild(ageInputGroupText);
                ageInputGroup.appendChild(ageInputGroupPrepend);
                ageInputGroup.appendChild(ageInput);
                ageCol.appendChild(ageLabel);
                ageCol.appendChild(ageInputGroup);
                
                return(ageCol.outerHTML);
            }

Then I call document.write(addInputGroup("12345", "18")); when I need to create an “age” input group.

Does this look correct?

SharePoint 2013 DOM dialog object

I’m using SP2013 and I am trying to refresh one of many list web parts on a page with the Manual Refresh button displayed for each list.

The current display view has four lists associated with it each with a Manual Refresh button displayed for each.

I am trying to refresh via JavaScript. Async Update is enabled as is Show Manual Refresh Button in the respective web parts.

My code works as long as the List Settings>Advanced Settings> Dialogs is set to NO. A full page view.

So, for example, document.querySelectorAll("#ManualRefresh") returns a usable object. So, the code to refresh for a specific web part looks as follows:

var myelement-document.querySelector("#WebPartWPQ6");
var refresh=myelement.querySelectorAll("#ManualRefresh");
myrefresh(0(.click();  

When in the console I run document.querySelectorAll("#ManualRefresh") I am returned an object which in my case has 4 elements since I have four ManualRefreash buttons on the page.

However, when Dialogs is set to Yes the document.querySelectorAll("#ManualRefresh") returns a Null object.

Seems I need to use something other than “document” in document.querySelectorAll statement to grab the DOM element from the dialog vs. the document. That is my assumption anyhow.

How do I access the dialog object vs. the document object and then use the queryselector as above modified to use a dialog vs. a page? If my nomenclature is wrong by all means correct me.

Thanks.

magento2 – Magento dom validation exception

I get this error on my product page and only for specific products.

Exception #0 (MagentoFrameworkConfigDomValidationException): Element 'handle': Character content other than whitespace is not allowed because the content type is 'element-only'.

The error is because the sku of the product is added in the layout xml like this:

<layout xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"><handle id="handle">479259<body>

Here the number 479259 is the sku and this should not be there. I disabled all my custom modules, even changed my theme to the default magento theme, changed to production mode, changed my database (the one on production doesn’t give this error) but I still get this error. Is there any way to find out where this sku is coming from?

The error I get in one of the logs is:

Cache file with merged layout: LAYOUT_frontend_STORE1_4e763528242bc7a0eb065e4d209735c84_page_layout_merged and handles default, catalog_product_view, catalog_product_view_type_configurable, catalog_product_view_id_117064, catalog_product_view_sku_479259, pl_thm_customtheme_default, pl_thm_customtheme_default_default, cms_noroute_index, cms_page_view, cms_noroute_index_id_collection, amshopbybase_swiper: Please correct the XML data and try again. Element 'handle': Character content other than whitespace is not allowed because the content type is 'element-only'.

Thank you for the help!

css – COMO SOLUCIONAR: Evita un tamaño excesivo de DOM

QUIERO QUE ALGUIEN ME AYUDE A SOLUCIONAR EL DIAGNOSTICO HECHO A MI PAGINA WEB EN https://developers.google.com/speed/pagespeed/insights/
RELACIONADO CON EVITAR UN TAMAÑO EXCESIVO DE DOM, A CONTINUACION DETALLO EL REGISTRO:

Total de elementos DOM
3028

Profundidad máxima de DOM

30

Número máximo de elementos secundarios

267

POR FAVOR PIDO AYUDA, PARA IMPLEMENTAR ESTA LINEA DE CODIGO, INDIQUEME POR FAVOR EN QUE CARPETA DE LA WEB SE MODIFICA, O COMO IMPLEMENTAR UN CODIGO MAS EFICIENTE Y COMO AGREGARLO CORRECTAMENTE.

GRACIAS